简体   繁体   中英

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)
{
}

Write:

dt.AcceptChanges(); 

after:

dt.Rows.Add(row);

To add column:

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

and its better to remove the it first:

dataGridView2.DataSource = dt;
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)
 {
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM