0
votes

I try to display data in the DataGridView in C# but it can't show anything at all. My DataGridView is inside a private static void function.

private static void processsub(Event a , Session session)
{ 
   List<String[]> lista = new List<string[]>();
   lista.add(new string[] {text1, text2, text3, text4, text5, text6, text7 });
   Form1 frm1 = newForm1();
   frm1.dataGridView1.AutoGenerateColumns=true;
   DataTable table = ConvertListtoDatTable(lista);
   frm1.dataGridview1.DataSource = table;
}

I used the messagebox window to display the " .Row[0].Cell[0].Value.ToString()" and it shows the right value but the DataGridView just didn't display the data.

Anyone have any suggestion?

1
Is it not frm1.dataGridView1 instead of frm.dataGridView1 ? - Edper
Sorry, it was my typo in here. - user2644434
Have you tried setting the AutoGenerateColumns flag after setting the DataSource? Oddly, the example code on MSDN goes through how to set this flag to false and add columns manually. - Zec
Have you tried to Debug your DataTable namely the "Table" variable if it has Rows to begin with? I know you said you did the Row[0].Cell[0] but just to be sure. - Edper
Edper, yes, I have tired debug my table and it got the right value as well. Zec, I tried to add column manually but it doesn't work either. Thanks - user2644434

1 Answers

0
votes

You may not spread rows.My test code is as the following.

   private void processsub()
    {
        List<String[]> lista = new List<string[]>();
        lista.Add(new string[] { "text1", "text2", "text3", "text4", "text5", "text6", "text7" });
        dataGridView1.AutoGenerateColumns = true;
        DataTable table = ConvertListtoDatTable(lista);
        dataGridView1.DataSource = table;
    }

    private DataTable ConvertListtoDatTable(List<String[]> lista)
    {
        DataTable table = new DataTable();
        int columnCount = lista[0].Length;
        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
        {
            table.Columns.Add();
        }
        foreach (string[] row in lista)
        {
            table.Rows.Add(row);
        }
        return table;
    }

    private void buttonTest_Click(object sender, EventArgs e)
    {
        processsub();
    }

Execute result: enter image description here