q4zar
q4zar

Reputation: 1

C#, DataGridView And DataTable

I have a small problem. I have never used DataTable or Datagridview before. With success i add a column names but when it comes to add row, all values are adding in one column. Here's the code:

StreamReader sr = new StreamReader(filename);
    DataTable table = new DataTable();
    string [] datarow;

    colt = sr.ReadLine();
    string[] columns = colt.Split(';');
    Count = columns.Length;

    foreach (string c in columns)
    {
        Table1.Columns.Add("Column", c);
        table.Columns.Add(c, typeof(String));
    }

    while (!sr.EndOfStream)
    {
        rowt = sr.ReadLine();
        datarow = rowt.Split(';');

        foreach (string a in datarow)
        {         
            table.Rows.Add(a);
            Table1.Rows.Add(a);
        }
    }
}

Upvotes: 0

Views: 88

Answers (1)

greenjaed
greenjaed

Reputation: 621

First, the reason that you're only seeing data being added to the first column is that the DataGridview.Add method adds an entire row to the table, not a single element. This is why everything is showing in the first column. To fix the problem, pass in the entire array like so:

table.Rows.Add(datarow);

Second, you shouldn't populate the DataGridView separate from the DataTable. This creates two copies of the data and any data that the user edits in the view will be out of sync with the DataTable. Instead, populate the DataTable and then bind it to the DataGridview. Any changes that the user makes will then be reflected in the DataTable. Your code would look something like this:

using (StreamReader sr = new StreamReader(filename))
{
    string [] datarow;

    colt = sr.ReadLine();
    string[] columns = colt.Split(';');
    Count = columns.Length;

    foreach (string c in columns)
    {
        table.Columns.Add(c, typeof(String));
    }

    while (!sr.EndOfStream)
    {
        rowt = sr.ReadLine();
        datarow = rowt.Split(';');
        table.Rows.Add(datarow);
    }
    Table1.DataSource = table;
}

Upvotes: 1

Related Questions