axzu fs axzu fs - 3 months ago 21
C# Question

Cannot add rows to datagridview Dynamically

DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dt.Columns.Add("name1", typeof(string));
dt.Columns.Add("name2", typeof(string));
dt.Columns.Add("name3", typeof(string));
dt.Columns.Add("name4", typeof(string));
dt.Columns.Add("name5", typeof(string));
for (int i = 0; i < 6; i++)
{
try
{
dr[i] = dt.Rows.Add();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
dataGridView1.DataSource = dt;


I'm getting error: "Cannot find column 5". If I will change
i < 6
to
i < 5
, everything works fine. How to add more than 5 rows? Thank you.

Answer

Try this:

    DataTable dt = new DataTable();
    dt.Columns.Add("name1", typeof(string));
    dt.Columns.Add("name2", typeof(string));
    dt.Columns.Add("name3", typeof(string));
    dt.Columns.Add("name4", typeof(string));
    dt.Columns.Add("name5", typeof(string));

    for (int i = 0; i < 6; i++)
    {
        try
        {
            dt.Rows.Add("a", "b", "c", "d", "e");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return;
        }
    }
    dataGridView1.DataSource = dt;
Comments