Question

my DataTable has over 1000 columns and I want to display values on the datagridview. Because of the FillWeigth problem I use the following method to fill the gridview,

public bool TransferDataTableToGrid(DataGridView dataGrid, DataTable dataTable)
    {
        dataGrid.SuspendLayout();

        if ((dataGrid != null) && (dataTable != null))
        {
            dataGrid.Columns.Clear();
            dataGrid.AutoGenerateColumns = false;
            dataGrid.DataSource = dataTable;

            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                DataGridViewColumn column = new DataGridViewColumn();
                column.Name = dataTable.Columns[i].ColumnName;
                column.FillWeight = 1;
                column.CellTemplate = new DataGridViewTextBoxCell();
                column.ValueType = dataTable.Columns[i].DataType;
                dataGrid.Columns.Add(column);
            }
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                for (int ii = 0; ii < dataTable.Rows.Count; ii++)
                {
                    dataGrid[i, ii].Value = dataTable.Rows[ii][i];
                }
            }
        }
        dataGrid.ResumeLayout();
        return true;
    }

and sometimes I have an effect that my gridview is empty. Only after second execution data is displayed. Do you have any ideas, why...?

Thanks.

Was it helpful?

Solution 3

Well, I solved my problem. With Ivan's suggestion I tried the alternative way to fill data: instead of using DataSource I add new rows manually

            foreach (DataRow row in dataTable.Rows)
            {
                var dataGridRow = new DataGridViewRow();
                dataGridRow.CreateCells(dataGrid);

                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    dataGridRow.Cells[i].Value = row.ItemArray[i];
                }

                dataGrid.Rows.Add(dataGridRow);
            }

...and it works - data in dgv is displayed. Thanks!

OTHER TIPS

I recommend to use paging, i mean that you can show about 20 columns with navigation buttons under your grid, it's like Google or others... even your are not programming a web application.

Use binding source to fill your grid

            SqlDataAdapter adapter = new SqlDataAdapter(database.cmd);
            dataSet1.Tables.Clear();
            adapter.Fill(dataSet1, "Table");
            bs = new BindingSource();
            bs.DataSource = dataSet1.Tables["Table"];
            dataGridView1.DataSource = bs;

now you dont need to worry about creating columns and fill cells in loops and its much better performance

Bind Data to Datagridview

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top