简体   繁体   English

将Gridview数据保存到数据库

[英]Saving Gridview Data To Database

I am having a Gridview which i want to save in my another table 我有一个Gridview我想保存在另一个表中

My Code is 我的代码是

protected void upload_Click(object sender, EventArgs e)
{
    string query1 = "INSERT INTO tbl_Pre_Y1_Bus1 (CRITICAL,SPECIFICATION, [1],[2],[3],[4],[5],TMLCAL) VALUES (@CRITICAL, @SPECIFICATION, @[1], @[2], @[3], @[4], @[5], @TMLCAL)";

    foreach (GridViewRow row in GridView2.Rows)
    {
        using (SqlCommand cmd = new SqlCommand(query1))
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@CRITICAL", row.Cells[0].ToString());
            cmd.Parameters.AddWithValue("@SPECIFICATION", row.Cells[1].ToString());
            cmd.Parameters.AddWithValue("@[1]", row.Cells[2].ToString());
            cmd.Parameters.AddWithValue("@[2]", row.Cells[3].ToString());
            cmd.Parameters.AddWithValue("@[3]", row.Cells[4].ToString());
            cmd.Parameters.AddWithValue("@[4]", row.Cells[5].ToString());
            cmd.Parameters.AddWithValue("@[5]", row.Cells[6].ToString());
            cmd.Parameters.AddWithValue("@TMLCAL",row.Cells[7].ToString());
         con.Open(); //here i am having an respected error
         cmd.ExecuteNonQuery();
         con.Close();
         Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }

    }
}

My error is "Object reference not set to an instance of an object." 我的错误是“对象引用未设置为对象的实例”。 help me to resolve this 帮我解决这个问题

Replace .ToString() with Convert.ToString as shown below. 如下所示,用Convert.ToString替换.ToString()。 It will handle blank as well as null value. 它将处理空白以及空值。 Then you can check why the value is coming null. 然后,您可以检查为什么值变为空。 You also need to add .Text as shown below. 您还需要添加.Text,如下所示。

cmd.Parameters.AddWithValue("@CRITICAL", Convert.ToString(row.Cells[0].Text));
cmd.Parameters.AddWithValue("@SPECIFICATION", Convert.ToString(row.Cells[1].Text));

Before calling .ToString() make sure that your object is not null, Also to read cell text you must put .Text Something like this : 在调用.ToString()之前,请确保您的对象不为null,此外,要读取单元格文本,您还必须将.Text放置如下:

    if (row.Cells[0] != null && !string.IsNullOrEmpty(row.Cells[0].Text)) {
     cmd.Parameters.AddWithValue("@CRITICAL", row.Cells[0].Text.ToString());

    } else {
     // Handle it
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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