2011-07-18 113 views
1

我试图在单击选择按钮时根据主键在我的数据库中显示行。根据所选索引从SQL数据库中选择行

<asp:Panel ID="pnlView" runat="server"> 
     <p> 
      <asp:Label ID="lblTitle" runat="server" Text="Label"></asp:Label></p> 
     <p> 
      <asp:Label ID="lblBody" runat="server" Text="Label"></asp:Label></p> 
    </asp:Panel> 
    <asp:GridView ID="GridView1" runat="server" DataSourceID="sdsDocuments" EnableModelValidation="True" 
     SelectedIndex="0" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"> 
     <Columns> 
      <asp:CommandField ShowSelectButton="True" /> 
     </Columns> 
    </asp:GridView> 



protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     lblTitle.Text = GridView1.SelectedRow.ToString(); 
     lblBody.Text = GridView1.SelectedIndex.ToString(); 

     SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["blcDocumentationConnectionString"].ConnectionString); 

     // Create Command Object 
     SqlCommand nonqueryCommand = thisConnection.CreateCommand(); 

     try 
     { 
      // Open Connection 
      thisConnection.Open(); 

      // Create INSERT statement with named parms 
      nonqueryCommand.CommandText = "SELECT DocumentTitle,DocumentBody FROM tblDocument WHERE DocumentID = @DocumentID"; 

      // Add parms to Command parms collection 
      nonqueryCommand.Parameters.Add("@DocumentID", SqlDbType.Int); 

      // Execute query statement 
      nonqueryCommand.ExecuteNonQuery(); 
     } 

     catch (SqlException ex) 
     { 
     } 

     finally 
     { 
      // Close Connection 
      thisConnection.Close(); 
     } 
+2

问题是? – Quassnoi

回答

2

GridView1_SelectedIndexChanged情况下,我不能看到你为你的参数设定值@DocumentID

替换此nonqueryCommand.Parameters.Add("@DocumentID", SqlDbType.Int);

与这一个nonqueryCommand.Parameters.AddWithValue("@DocumentID", GridView1.SelectedValue);

编辑:继您的评论,您还需要显示您的标签中的文字,像...

GridViewRow row = GridView1.SelectedRow; 
lblTitle.Text = row.Cells[TitleCellIndex].Text; 
lblBody.Text = row.Cells[BodyCellIndex].Text 
+0

谢谢,我现在如何填充lblTitle&lblBody? – bluetickk

+0

更新回答,现在检查:) –

+0

Muhammad,这只填充gridview中的表格。我需要它们直接来自数据库。有没有办法让他们从存储过程到标签? – bluetickk

1

您没有将值传递给您的SQL参数的documentid。如果您的网格填充正确,则当前行值位于EventArgs e变量内。