[英]How can I use a WHERE clause in GridView control?
我想創建一個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>
您可以調用此方法來綁定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();
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.