【问题标题】:How to bind gridview at pageload with dropdown list如何在页面加载时将gridview与下拉列表绑定
【发布时间】:2013-07-22 13:52:12
【问题描述】:

我有一个按类别搜索的下拉列表。 我需要帮助在页面加载时绑定我的 gridview,但同时,我也有一个选择命令作为投票。 我知道pageload事件中有Databinding之类的代码。但就我而言,我需要将选择命令链接到一个按钮来更新投票。如果我对它进行数据绑定,我无法获取数据键名来更新我的投票计数器。 有什么方法可以绑定gridview,而不需要删除gridview本身的DataSourceID?

我的aspx代码如下。

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                        SelectCommand="SELECT * FROM [Review] WHERE ([Category] = @Category)">
                        <SelectParameters>
                            <asp:ControlParameter ControlID="ddlCat" Name="Category" 
                                PropertyName="SelectedValue" Type="String" />
                        </SelectParameters>
                    </asp:SqlDataSource>



                      <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                        SelectCommand="SELECT [Category] FROM [ReviewCategory]">
                        </asp:SqlDataSource>


                    <asp:DropDownList ID="ddlCat" runat="server" 
                        DataSourceID="SqlDataSource2" DataTextField="Category" 
                        DataValueField="Category" AutoPostBack="True" 
                        onselectedindexchanged="SelectionChange">
                    </asp:DropDownList>


<asp:GridView ID="GridView1" runat="server" Width="1114px" 
    Height="272px" AutoGenerateColumns="False" PageSize="5" 
        DataSourceID="SqlDataSource1" AllowPaging="True" DataKeyNames="ReviewID">
<Columns>

    <asp:BoundField DataField="Votes" HeaderText="Votes" 
        SortExpression="Votes" />
    <asp:BoundField DataField="Category" HeaderText="Category" 
        SortExpression="Category" />

    <asp:CommandField SelectText="VOTE as your FAVOURITE!" 
        ShowSelectButton="True" />
</Columns>

c#代码

 protected void btnVote_Click(object sender, EventArgs e)
{
    int reviewid = Convert.ToInt16(GridView1.SelectedDataKey.Value);

    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
    string sqlstmt = "select Votes from Review where ReviewID = '" + reviewid + "'";
    SqlCommand comm = new SqlCommand(sqlstmt, conn);


    try
    {

        conn.Open();
        SqlDataReader read = comm.ExecuteReader();


        if (read.Read())
        {
            int votes = (int)read["Votes"];
            votes += 1;
            string updatestatement = "Update Review set Votes= '" + votes + "' Where ReviewID = '" + reviewid + "'";
            SqlCommand command = new SqlCommand(updatestatement, conn);
           read.Close();
            command.ExecuteNonQuery();
        }


    }
    finally { 
        conn.Close();
        GridView1.DataBind();
    }

}

     protected void SelectionChange(object sender, EventArgs e)
  {

    int stored = ddlCat.SelectedIndex;

    if (stored == 0)
    {
        SqlDataSource1.SelectCommand = "SELECT * from Review ORDER BY [Votes] DESC  ";


    }
    else { } 
}

【问题讨论】:

    标签: c# asp.net visual-studio-2010 gridview


    【解决方案1】:

    您应该从 GridView 实现 RowCommand 事件。您已经拥有CommandField,所以请执行以下操作:

    void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
      //
      // Get the keys from the selected row
      //
      LinkButton lnkBtn = (LinkButton)e.CommandSource;    //the button
      GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  //the row
      GridView myGrid = (GridView)sender; // the gridview
      int reviewid = Convert.ToInt32(GridView1.DataKeys[myRow.RowIndex].Value); //value of the datakey **strong text**
    
      // If multiple buttons are used in a GridView control, use the
      // CommandName property to determine which button was clicked.
      // In this case you are pressing the button Select, as ou already
      // defined this at the aspx code.
      if(e.CommandName=="Select")
      {
        // Put the logic from btnVote_Click here
      }
    }
    

    另一种方法是实现SelectIndexChangingSelectIndexChanged,因为您将使用选择按钮来触发更新魔法。这里是SelectIndexChanging的例子。

    void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
    {
    
      // Get the currently selected row. Because the SelectedIndexChanging event
      // occurs before the select operation in the GridView control, the
      // SelectedRow property cannot be used. Instead, use the Rows collection
      // and the NewSelectedIndex property of the e argument passed to this 
      // event handler.
      int reviewid = Convert.ToInt32(GridView1.DataKeys[e.NewSelectedIndex].Value); //value of the datakey **strong text**
    
      // Put the logic from btnVote_Click here
    }
    

    【讨论】:

      【解决方案2】:

      让我们一一研究您的要求:

      1.) *在 PageLoad 中使用 DropDownList 绑定 GridView:

      在这种情况下,您需要检索在下拉列表中选择的值。执行以下设置以从 DropDownList 中获取值

      <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
       ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
       SelectCommand="SELECT [Category] FROM [ReviewCategory] where Category=@Category">
      <SelectParameters><asp:ControlParameter ControlID="ddlCat" Name="Category"
       PropertyName="SelectedValue" /></SelectParameters>
      </asp:SqlDataSource>
      

      发生了什么:

      • 每次在下拉列表中选择一个值时,都会发生回发(AutoPostback="true")。
      • 在 Page.PreRender 事件之后,DataSource 控件 [ 此处为 SqlDatSource ] 执行所需的查询并检索数据。所以选择的 DropDownList 值将被 SqlDataSource 使用。因此,无需担心以任何方式更改/操作 DataSourceID。

      2.) “但就我而言,我需要将选择命令链接到一个按钮以更新投票” '

      在这种情况下,您在网格视图内有一个“选择”按钮,在 GridView 外但在您的页面某处有一个“投票”按钮。因此,一旦您在网格视图中选择任何行,请单击“投票”按钮。您可以照常访问 SelectedRow 和 Index。

      protected void btnVote_Click1(object sender, EventArgs e)
      {
           int i = CustomersGridView.SelectedIndex;
      }
      

      请注意,“投票”按钮的 Click 事件在 DataSource 控件执行查询和检索数据之前触发。因此,一旦您像当前一样更新 btnVote_click 事件中的投票计数,就无需再次绑定数据。您的这部分代码对我来说似乎很好。

      【讨论】:

      • 我试过你的方法..在sqlsoruce 2中添加控件样式后,我的下拉列表值消失了..为什么会这样
      • Dropdownlist 值消失?您正在使用 "SqlDataSource2" 获取 dropDownList 中的数据。那么你能检查一下这第二个 dataSource 确实在获取数据吗?由于您在 SqlDataSource2 中没有进行任何更改,它应该获取数据。
      猜你喜欢
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      相关资源
      最近更新 更多