Set columns width in a datagrid using Compact Framework

亡梦爱人 提交于 2019-11-29 03:10:39

问题


I'm trying to set the width of the columns in my datagrid. I use Compact Framework 2.0 and C#

I tried this but it gives me an "out of bonds" error message:

foreach (DataGridColumnStyle vColumnStyle in dataGrid1.TableStyles[0].GridColumnStyles)
{
    vColumnStyle.Width = 100;
}

Here is the code for filling my datagrid with the datatable (only fails when I try to set the columns width):

void FillData()
{
    // 1
    // Open connection
    string conString = "Data Source=\\Program Files\\smartdeviceproject2\\repartocrack.sdf";
    using (SqlCeConnection c = new SqlCeConnection(conString))
    {
        c.Open();
        // 2
        // Create new DataAdapter
        using (SqlCeDataAdapter a = new SqlCeDataAdapter(
        "SELECT codbultocomp, nombre, estado FROM envios INNER JOIN tiendas ON envios.codigodestino = tiendas.codigodestino", c))
        {
            // 3
            // Use DataAdapter to fill DataTable
            DataTable t = new DataTable();
            a.Fill(t);
            // 4
            // Render data onto the screen
            foreach (DataGridColumnStyle vColumnStyle in dataGrid1.TableStyles[0].GridColumnStyles)
            {
                vColumnStyle.Width = 100;
            }
            dataGrid1.DataSource = t;
        }
    }
}

回答1:


Try this code:

dataGrid1.TableStyles.Clear();
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = t.TableName;
foreach (DataColumn item in t.Columns)
{
    DataGridTextBoxColumn tbcName = new DataGridTextBoxColumn();
    tbcName.Width = 100;
    tbcName.MappingName = item.ColumnName;
    tbcName.HeaderText = item.ColumnName;
    tableStyle.GridColumnStyles.Add(tbcName);
 }
 dataGrid1.TableStyles.Add(tableStyle);



回答2:


DataGrid is now obsolete but I encountered the same problem when changing some legacy code so I'll post my solution.

The problem is that DataGrid has a private field called myGridTable that is holding the current DataGridTableStyle. A current DataGridTableStyle exists even if the TableStyles collection is empty, in which case it points to a default DataGridTableStyle which is also private/internal.

Since DataGrid is obsolete anyway and won't be changed, I decided to just use Reflection to access those private fields. They should have been public anyway and making them private was a bad design decision IMO.

The advantage of working with the current styles directly is you don't need to destroy and recreate the table styles just to change the widths, and it works without unexpected behavior every time.

I created a few extension methods to do it:

static class DataGridColumnWidthExtensions
{
    public static DataGridTableStyle GetCurrentTableStyle(this DataGrid grid)
    {
        FieldInfo[] fields = grid.GetType().GetFields(
                     BindingFlags.NonPublic |
                     BindingFlags.Instance);

        return (DataGridTableStyle)fields.First(item => item.Name == "myGridTable").GetValue(grid);
    }

    public static IList<int> GetColumnWidths(this DataGrid grid)
    {
        var styles = grid.GetCurrentTableStyle().GridColumnStyles;

        var widths = new int[styles.Count];
        for (int ii = 0; ii < widths.Length; ii++)
        {
            widths[ii] = styles[ii].Width;
        }

        return widths;
    }

    public static void SetColumnWidths(this DataGrid grid, IList<int> widths)
    {
        var styles = grid.GetCurrentTableStyle().GridColumnStyles;

        for (int ii = 0; ii < widths.Count; ii++)
        {
            styles[ii].Width = widths[ii];
        }
    }
}



回答3:


I spent a better part of 2 days looking for the answer above. Thanks for the great solutions provided. Here is some vb code, with a customization of column widths by column:

    ' trgAppt is defined as system.windows.forms.datagrid
    trgAppt.TableStyles.Clear()
    Dim tableStyle As DataGridTableStyle
    tableStyle = New DataGridTableStyle
    tableStyle.MappingName = dtAppt.TableName
   For Each myItem As DataColumn In dtAppt.Columns
    Dim tbcName As DataGridTextBoxColumn = New DataGridTextBoxColumn
    Select Case myItem.ColumnName.ToString.ToUpper
     Case "STOP"
       tbcName.Width = 35
     Case "ORDER"
       tbcName.Width = 45
     Case "CUSTOMER"
       tbcName.Width = 70
     Case "QTY"
       tbcName.Width = 35
    End Select
    tbcName.MappingName = myItem.ColumnName
    tbcName.HeaderText = myItem.ColumnName
    tableStyle.GridColumnStyles.Add(tbcName)
    tbcName = Nothing
   Next
    trgAppt.TableStyles.Add(tableStyle)
    trgAppt.DataSource = dtAppt


来源:https://stackoverflow.com/questions/6829570/set-columns-width-in-a-datagrid-using-compact-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!