Harvey
Harvey

Reputation: 389

How to add row in DataGridView programmatically

Here I've tried this code. But, my problem now is that, it doesn't display any data.

Here is my code

try
{
    DataTable dt = new DataTable();
    con.Open();

    dt.Load(new MySqlCommand("SELECT variant_name FROM tblVariant_Product WHERE product_name='" + cboProduct.Text + "'", con).ExecuteReader());

    DataColumn col = dt.Columns.Add(new DataColumn("Quantity", typeof(Int32));
    col.AllowDBNull = false;

    DataRow row = dt.NewRow();
    row["variant_name"] = "TOTAL";
    row["quantity"] = 0;
    dt.Rows.Add(row);

    dataGridView2.DataSource = dt;
    con.Close();
}
catch (Exception)
{
}

Upvotes: 0

Views: 2737

Answers (3)

Harvey
Harvey

Reputation: 389

try{
    DataTable dt = new DataTable();
    con.Open();

    dt.Load(new MySqlCommand("SELECT variant_name FROM tblVariant_Product WHERE product_name='" + cboProduct.Text + "'", con).ExecuteReader());

    dt.Columns.Add(new DataColumn("Quantity", typeof(Int32));

    DataRow row = dt.NewRow();
    row["variant_name"] = "TOTAL";
    row["quantity"] = 0;
    dt.Rows.Add(row);

    dataGridView2.DataSource = dt;
    con.Close();
 }
 catch (Exception)
 {
 }

Upvotes: 0

DevProve
DevProve

Reputation: 192

To add column:

dt.Columns.Add(new DataColumn("ColumnName",Type.GetType("System.String")));

and its better to remove the it first:

dataGridView2.DataSource = dt;

Upvotes: 0

Abhishek B Patel
Abhishek B Patel

Reputation: 935

Write:

dt.AcceptChanges(); 

after:

dt.Rows.Add(row);

Upvotes: 3

Related Questions