2013-10-14 63 views
0

我有一個GridView如下插入數據時的選擇按鈕,用戶點擊GridView的

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

背後的GridView 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"); 

      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中選擇的值,使用select按鈕和inse rt該按鈕單擊事件選定的值....但與上述代碼,它不工作...

任何人都可以建議我一些其他的想法或如果可能與這些代碼,然後如何......你能給我它的代碼....非常感謝

回答

1

您可以添加隱藏字段並將GridView的rowindex保存在隱藏字段中。在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(); 
      } 
     } 
    } 
} 
+0

我試試你的代碼,我的事要告訴你,我有按鈕不ImageButton的,所以我GridViewRow gvr =(GridViewRow)(((Button)e.CommandSource).NamingContainer);但仍然當我在按鈕單擊事件調試時,btn的值爲空....會發生什麼錯誤....? – Pratik

+0

它工作正常......謝謝 – Pratik

0

我認爲你有興趣插入一個基於從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)。

相關問題