【问题标题】:How to pass my hidden primary key value in a gridview to a stored procedure?如何将网格视图中隐藏的主键值传递给存储过程?
【发布时间】:2024-05-23 17:40:02
【问题描述】:

从技术上讲,我在 gridview 中有 5 列

  1. 编辑和停用按钮
  2. 姓名
  3. 电话
  4. 电子邮件
  5. [隐藏] 用户 ID“这是我在桌子上的主键”

我想将此选定行的用户 ID 值传递给我的更新存储过程,该过程将设置 active=0,其中 userid=@userid。

不确定是否有办法传递选定的数据键或仅传递选定的行隐藏列 4,这将是索引中的 5,或者您是否有任何其他更好的方法。

protected void gvRowDeleting2(object sender, GridViewDeleteEventArgs e)
{

    String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "usp_update_user_active";
    cmd.Parameters.Add("@userid", SqlDbType.VarChar).Value = userID; ******NEED HELP HERE****

    cmd.Connection = con;

    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        buildcontractoradmingv();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        /*Display message saying company is deactivated*/
        string message = "User has been removed";
        string script = "window.onload = function(){ alert('";
        script += message;
        script += "')};";
        ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
        con.Close();
        con.Dispose();
    }
}

【问题讨论】:

标签: c# asp.net .net webforms


【解决方案1】:

你可以试试这个:

string UserID = YourGrid.Rows[e.RowIndex].Cells[IndexOfHiddenCol].Text;

【讨论】:

  • 谢谢!它工作“字符串 UserID = YourGrid.Rows[e.RowIndex].Cells[4].Text;
  • 没有潜在朋友:)
【解决方案2】:

最简单的方法是将userID 作为DataKeyNames 添加到GridView。 userID 在这种情况下是绑定到 GridView 的源的数据库列或属性。

<asp:GridView ID="GridView1" runat="server" DataKeyNames="userID"

然后在delete方法中从DataKeys中获取值。

int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

或者您可以将Label 添加到TemplateField,并将可见性设置为false

<asp:Label ID="Label1" runat="server" Text='<%# Eval("userID") %>' Visible="false"></asp:Label>

然后通过使用FindControl查找标签并读取它的文本来获取代码中的值。

Label label = GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;
int userID = Convert.ToInt32(label.Text);

【讨论】:

  • 您好,我尝试了第一种方法并收到此消息。 “索引超出范围。必须为非负数且小于集合的大小。\r\n参数名称:索引”values[0] 中的 0 也指什么?我会尝试第二种方式并报告
  • 你添加DataKeyNames到GridView了吗?
  • 是的,我做到了。我尝试了这两种方法,但仍然有同样的问题。这对隐藏列有效吗?您想查看更多代码吗?
  • 我在下面的答案中使用了代码并且它有效。感谢您抽出时间提供帮助