根据所选索引从SQL数据库中选择行
本文关键字:数据库 选择 SQL 索引 | 更新日期: 2023-09-27 18:02:20
当单击选择按钮时,我试图根据主键显示数据库中的行。
<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();
}
在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
您没有将值传递给文档id的SQL参数。如果您已经正确地填充了网格,那么当前行值将在EventArgs e变量中。