0

I have a gridview as below

 <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" />

Code behind gridview rowcommand is as below

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();
                 }
             }
        }


    }

Code behind the button click event is as below

 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();
                }          
            }
        }
}

I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...

Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot

2 Answers 2

1

You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:

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

In code, gvDoctorList_RowCommand method:

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 method:

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();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I try your code I thing want to inform you that I have button not imagebutton so i have make change in line GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer); but still when i debug on button click event the value of btn is null....what would be wrong....?
0

I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?

What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:

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

Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:

string pIDstr = gvDoctorList.SelectedValue.ToString();

Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.