【问题标题】:Select row from SQL database depending on selected Index根据所选索引从 SQL 数据库中选择行
【发布时间】:2011-07-18 15:29:35
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    在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 
    

    【讨论】:

    • 谢谢,我现在如何填充 lblTitle 和 lblBody?
    • Muhammad,这只会填充来自 gridview 的表格。我需要它们直接来自数据库。有没有办法让它们从存储过程到标签?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2018-02-08
      • 2019-02-21
      • 2012-10-07
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 2019-01-01
      • 2013-10-09
      相关资源
      最近更新 更多