MudBlazor DataGrid Default Column Width

1k Views Asked by At

I have a MudBlazor DataGrid and some of the cells have a long string of text. By default, MudBlazor will make the column width the length of the longest cell value. I want the default column width to be a specific width, like 100px, and the user can resize the column if need be to see the extra text. I also don't want the text to wrap to a new line. This is how it works in Excel. I am struggling to figure out how to do this.

I have tried using the CellStyle and HeaderStyle and haven't had much luck. I made a basic DataGrid to display this issue. Below is my code for that:

<div style="width: 50vw;">
  <MudDataGrid T="Person" Items="@People" ColumnResizeMode="ResizeMode.Container">
    <Columns>
      <PropertyColumn Property="x => x.Name" CellStyle="width: 100px; overflow-x: hidden; white-space: nowrap;" />
      <PropertyColumn Property="x => x.State" CellStyle="width: 100px; overflow-x: hidden; white-space: nowrap;" />
      <PropertyColumn Property="x => x.Age" CellStyle="width: 100px; overflow-x: hidden; white-space: nowrap;" />
    </Columns>
  </MudDataGrid>
</div>

@code {

  private IEnumerable<Person> People = new List<Person>
  {
    new Person("Brady", 25, "Florida"),
    new Person("Tim", 32, "Minnesota"),
    new Person("Derek", 51, "Utahqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"),
    new Person("Ben", 27, "Wisconsin"),
    new Person("Sam", 34, "Alaska")
  };

}

Here is what the output looks like for the above code:

In Excel, the columns can have a set width. If text inside of a cell is longer than the column width, it just gets cut off. The user needs to adjust the column width to see the additional text. This is what I'm looking to do in my DataGrid.

Here is what it looks like in Excel and what I'm trying to do.

1

There are 1 best solutions below

1
On BEST ANSWER

You need to use max-width CSS property instead of width.

<div style="width: 50vw;">
  <MudDataGrid T="Person" Items="@People" ColumnResizeMode="ResizeMode.Container">
    <Columns>
      <PropertyColumn Property="x => x.Name" CellStyle="max-width: 100px; overflow-x: hidden; white-space: nowrap;" />
      <PropertyColumn Property="x => x.State" CellStyle="max-width: 100px; overflow-x: hidden; white-space: nowrap;" />
      <PropertyColumn Property="x => x.Age" CellStyle="max-width: 100px; overflow-x: hidden; white-space: nowrap;" />
    </Columns>
  </MudDataGrid>
</div>

@code {

  private IEnumerable<Person> People = new List<Person>
  {
    new Person("Brady", 25, "Florida"),
    new Person("Tim", 32, "Minnesota"),
    new Person("Derek", 51, "Utahqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"),
    new Person("Ben", 27, "Wisconsin"),
    new Person("Sam", 34, "Alaska")
  };
    public record Person(string Name, int Age, string State);
}
Generates

Example

MudBlazor snippet