1

我有一个按类别搜索的下拉列表。我需要帮助在页面加载时绑定我的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 { } 
}
4

2 回答 2

1

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

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 事件中的投票计数,就无需再次绑定数据。你的这部分代码对我来说似乎很好。

于 2013-07-22T17:24:10.980 回答
1

您应该RowCommand从 GridView 实现事件。你已经有了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
  }
}

另一种方法是实现SelectIndexChangingor SelectIndexChanged,因为您将使用 Select Button 来触发更新魔法。这里以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
}
于 2013-07-22T14:26:40.473 回答