我想创建一个where子句,以便我可以使用我在页面加载时存储在ViewState中的某个特定id从数据库中获取值到gridview。 Where子句在代码中的星号中标记
<asp:GridView ID="gvView" runat="server" AutoGenerateColumns="false" DataKeyNames="ID"
DataSourceID="SqlDataSource" AllowPaging="true" PageSize="50" Width="100%"
EmptyDataText="--- No records yet. ---" PagerStyle-HorizontalAlign="Center" PagerSettings-PageButtonCount="5"
EmptyDataRowStyle-ForeColor="#888581" EmptyDataRowStyle-Font-Size="14px" EmptyDataRowStyle-Height="30px"
EmptyDataRowStyle-Font-Italic="true" AlternatingRowStyle-BackColor="#E2E2E2"
PagerStyle-CssClass="pager">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="RowSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="false" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource" runat="server"
ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ID, Title FROM Table **WHERE AnotherID=@AnotherID** ORDER BY ID">
</asp:SqlDataSource>
答案 0 :(得分:0)
您可以调用此方法绑定您的gridview
protected void BindGridview(int anotherid)
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=source;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ID, Title FROM Table WHERE AnotherID='"+anotherid+"' ORDER BY ID", con);
SqlDataAdapter da*emphasized text* = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
gvView.DataSource = ds;
gvView.DataBind();
}
如果要与sqldatasource绑定
SqlDataSource SqlDataSource = new SqlDataSource();
SqlDataSource.ID = "SqlDataSource";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlDataSource.SelectCommand = "SELECT ID, Title FROM Table WHERE AnotherID='"+anotherid+"' ORDER BY ID";
gvView.DataSource = SqlDataSource;
gvView.DataBind();
答案 1 :(得分:0)
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT ID, Title FROM Table WHERE WHERE [AnotherID] = '" + @anotherid + "' ORDER BY ID ">
<SelectParameters>
<asp:Parameter DefaultValue='<%# ViewState("ViewStateID") %>' Name="anotherid" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>