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