hiii
how to reduce the column size of the datagrid based on the data present in that column

Dani AI

Generated

Both of the quick fixes already suggested in this thread are valid depending on the environment: the designer approach mentioned by is fine for static layouts, and the autosize idea raised by is the right direction when you want runtime sizing. The important distinction is whether this is a WinForms DataGridView or an ASP.NET WebForms GridView/DataGrid — they behave differently and need different solutions.

For WinForms DataGridView you can let the control size itself at runtime (easy and accurate). Example in VB.NET:

' Autosize visible columns to fit cell contents
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells

' Or autosize a single column (index 2)
DataGridView1.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells

For ASP.NET GridView/DataGrid the browser decides column width. To "shrink to content" you normally remove fixed widths and use table-layout:auto. For long values, prefer CSS wrapping or truncation instead of trying to measure exact pixels. If a server-side estimate is required (rough), compute the longest cell text after binding and set the column ItemStyle width (works when you use explicit BoundFields):

' After GridView1.DataBind()
Dim maxLen As Integer = 0
For Each r As GridViewRow In GridView1.Rows
    Dim s As String = Server.HtmlDecode(r.Cells(colIndex).Text)
    If s.Length > maxLen Then maxLen = s.Length
Next
Dim px As Integer = Math.Max(50, Math.Min(600, maxLen * 7)) ' rough char->px estimate
GridView1.Columns(colIndex).ItemStyle.Width = Unit.Pixel(px)

Notes: measuring with Graphics.MeasureString is more accurate but heavier and not ideal on web servers. Autosize calls can be slow on large result sets. Also check header text, padding, images or HTML in cells — those often force extra width.

Hi .. First click on the small arrow.
then click on the edit columns
then select the column u want to resize
finally on the properties window u wil find the width column
just increase or decrease

Hi right click the datagrid, then select edit column, then in left panel of that window , select the column you want to edit, then in right panel select layout/AutiSizeMode/DisplayedCells.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.