从SQL数据库中选择行,具体取决于所选索引

时间:2011-07-18 15:29:35

标签: c# .net asp.net sql gridview

单击“选择”按钮时,我尝试根据主键显示数据库中的行。

<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 个答案:

答案 0 :(得分: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 

答案 1 :(得分:1)

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