当用户单击网格视图中的选择按钮时插入数据

本文关键字:按钮 选择 插入 数据 用户 单击 网格 视图 | 更新日期: 2023-09-27 18:35:17

>我有一个网格视图如下

 <asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
                            AllowPaging="True" AllowSorting="True" 
                             OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
                                        <asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
                                        <asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
                                <asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
                                <asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
                                <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
                            </Columns>
                        </asp:GridView>
                        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" 
                            SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />

网格视图行命令背后的代码如下所示

protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int pID = Convert.ToInt32(e.CommandArgument);
            Session["PatientId"] = Convert.ToString(e.CommandArgument);
            //Server.Transfer("Patientstaticformatrix.aspx");
             string pIDstr = Convert.ToString(Session["PatientId"]);
             if (!string.IsNullOrEmpty(pIDstr))
             {
                 int patientID = Convert.ToInt32(pID);
                 //string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                 string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
                 string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                 using(SqlConnection conn = new SqlConnection(connection))
                 {
                     //SqlConnection conn = new SqlConnection(con);
                     DataSet ds;
                     ds = new DataSet();
                     SqlDataAdapter cmpatientexam;
                     conn.Open();
                     cmpatientexam = new SqlDataAdapter(sqlquery, conn);
                     cmpatientexam.Fill(ds, "PatientExam");
                     TreeNode pidnode = new TreeNode();
                     pidnode.Text = pIDstr;

                     foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
                     {
                             //TreeNode tvpatexam = new TreeNode();
                             //tvpatexam.Text = patrow["PId"].ToString();
                             //TreeView1.Nodes.Add(tvpatexam);
                             //for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
                             //if (patrow["PId"].ToString() != DBNull.Value)
                             //{                               
                                 TreeNode childtvpatexam = new TreeNode();
                                 childtvpatexam.Text = patrow["Exam"].ToString();
                                 pidnode.ChildNodes.Add(childtvpatexam);
                                 //break;
                             //}
                         //TreeView1.Nodes.Add(tvpatexam);
                     }
                     TreeView1.Nodes.Add(pidnode);
                     ds.Dispose();
                     cmpatientexam.Dispose();
                     conn.Close();
                     conn.Dispose();
                 }
             }
        }

    }

按钮单击事件背后的代码如下所示

 protected void btnformatric_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in gvDoctorList.Rows)
        {
            Button btn = (Button)row.FindControl("Select");
            if (btn != null)
            {
                string pIDstr = Convert.ToString(Session["PatientId"]);
                string exam = ((Button)sender).Text;
                SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (@pid,@exam)", con);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                try
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@pid", pIDstr);
                    cmd.Parameters.AddWithValue("@exam", exam);

                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Response.Write("Error Occured: " + ex.Message.ToString());
                }
                finally
                {
                    con.Close();
                    cmd.Dispose();
                }          
            }
        }
}

我想使用选择按钮插入从网格视图中选择的值,并在按钮单击事件中插入该选定值....但是使用上面的代码它不起作用...

任何人都可以向我建议一些其他想法,或者如果可能的话,使用这些代码,然后如何......你能给我它的代码吗?多谢

当用户单击网格视图中的选择按钮时插入数据

您可以添加隐藏字段并将 Gridview 的行索引保存在隐藏字段中。在btnformatric_Click中,您可以按索引获取行并获取数据。标记:

 <asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
 <asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />

在代码中,gvDoctorList_RowCommand方法:

protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                int pID = Convert.ToInt32(e.CommandArgument);
                Session["PatientId"] = Convert.ToString(e.CommandArgument);
                //Server.Transfer("Patientstaticformatrix.aspx");
                GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ...     ... ... ...     ... ... ...     ... ... ...     ... ... ... 

btnformatric_Click方法:

protected void btnformatric_Click(object sender, EventArgs e)
{
    int rowIndex = 0;
    if (int.TryParse(hdnRowIndex.Value, out rowIndex))
    {
        //Get the row
        GridViewRow row = gvDoctorList.Rows[rowIndex];            
        Button btn = (Button)row.FindControl("Select");
        if (btn != null)
        {
            string pIDstr = Convert.ToString(Session["PatientId"]);
            string exam = ((Button)sender).Text;
            SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (@pid,@exam)", con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            try
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@pid", pIDstr);
                cmd.Parameters.AddWithValue("@exam", exam);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Response.Write("Error Occured: " + ex.Message.ToString());
            }
            finally
            {
                con.Close();
                cmd.Dispose();
            }
        }
    }
}

我假设您有兴趣根据 GridView 中选定的PatientID值插入记录?

您要做的是首先将 GridView 的 DataKeyNames 属性设置为如下所示PatientID

<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>

然后在 btnformatric_Click 事件处理程序中,您可以通过 gvDoctorList.SelectedValue 获取选定的PatientID值,如下所示:

string pIDstr = gvDoctorList.SelectedValue.ToString();

当然,在执行上述操作之前,您应该检查以确保用户已从网格中选择患者(即该gvDoctorList.SelectedIndex >= 0)。