2011-07-18 110 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變量內。