繁体   English   中英

从数据库获取一个单元格的值到一个字符串中:我不能仅从下一行就从当前行中获取它

[英]Getting a value of a cell from database into a string: I can't get it from the current row just from the next one

问题是我只能从下一行访问某一行的值。 这是代码:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int s = GridView1.EditIndex;
            string constr = "con string";
            string statment = "Select Name from tb1 Where [ID] = " + s;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand comm = new SqlCommand(statment, con))
                {
                    con.Open();
                    Label2.Text = comm.ExecuteScalar().ToString();
                    con.Close();
                }
            }
        }

例如:

                   ID   Name
Edit Delete Select  1   JOhn 
Edit Delete Select  2   SMith

  • 如果单击第一行上的“编辑并更新”,则会显示以下内容:

    你调用的对象是空的。

  • 如果单击第二行上的编辑和更新,则从第一行获取值。
有没有什么办法解决这一问题?

更改int sd = GridView1.EditIndex; int sd = GridView1.EditIndex + 1;

更好的方法是使用gridview的datakeynames属性。

在gridview上设置datakeyname="id"将允许您使用int Id = Convert.ToInt32(GridView1.DataKeys[Gridview1.EditIndex].Values[0])检索ID。

与创建对象并将其设置为包含ID的行中的控件以获取其值相比,这将减少开销。 有关实现数据密钥名的更多信息,请参见链接

我还建议对SQL方法使用System.Data.SqlClient.SqlCommand并通过参数添加Id。 这将有助于防止注入攻击。

您使用了错误的ID。 EditIndex引用您正在编辑的项目的ROW号。 您必须从绑定的实体获取ID,然后传递该ID。

我不确定您要使用SQL做什么,但这并不重要。 SQL表具有一个ID字段,看起来该ID值可能已使用Label绑定到了GridView。 您必须使用RowIndex传递到您的SQL语句中,以获取该ID,因为SQL表中的ID可能不必与行索引对齐。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  // get the row being updated
  GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

  // use the FindControl method to retrieve the control holding the ID
  Label lbl = (Label)row.FindControl("lblid");

  // you can find other controls as needed using the same method
  TextBox tb1 = (TextBox)row.FindControl("textbox1");
  TextBox tb2 = (TextBox)row.FindControl("textbox2");

  // perform the SQL update, or whatever using the ID (here's your original code)

  string constr = "con string";          
  string statment = "Select Name from tb1 Where [ID] = " + lbl.Text;          
  using (SqlConnection con = new SqlConnection(constr))          
  {          
    using (SqlCommand comm = new SqlCommand(statment, con))          
    {          
      con.Open();          
      Label2.Text = comm.ExecuteScalar().ToString();          
      con.Close();          
    }          
  } 
}

暂无
暂无

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

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