bluetickk
bluetickk

Reputation: 689

Select row from SQL database depending on selected Index

I am trying to display rows from my database based on the primary key when the select button is clicked.

<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();
        }

Upvotes: 1

Views: 2216

Answers (2)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

In the GridView1_SelectedIndexChanged event, I can't see that you have set value for your parameter @DocumentID

Replace this nonqueryCommand.Parameters.Add("@DocumentID", SqlDbType.Int);

with this one nonqueryCommand.Parameters.AddWithValue("@DocumentID", GridView1.SelectedValue);

Edit: Following your comment, that you also need to display the text in your label, do like...

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

Upvotes: 2

Rich M
Rich M

Reputation: 387

You are not passing a value in to your SQL parameter for the documentid. If you have your grid populated correctly, the current row value is inside the EventArgs e variable.

Upvotes: 1

Related Questions