DataGrid學習3
發(fā)表時間:2024-05-22 來源:明輝站整理相關軟件相關文章人氣:
[摘要]上一例中靜態(tài)填充選擇框的值,但這不太適合那些值在數(shù)據(jù)庫中會更改的情況。因為 select HtmlControl 也支持 IEnumerable DataSource 屬性,可以轉而使用選擇查詢動態(tài)填充選擇框,這將保證數(shù)據(jù)庫和用戶界面始終同步。下面的示例說明此過程。<%@ Import Na...
上一例中靜態(tài)填充選擇框的值,但這不太適合那些值在數(shù)據(jù)庫中會更改的情況。因為 select HtmlControl 也支持 IEnumerable
DataSource 屬性,可以轉而使用選擇查詢動態(tài)填充選擇框,這將保證數(shù)據(jù)庫和用戶界面始終同步。下面的示例說明此過程。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
SqlConnection myConnection;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");
if (!IsPostBack)
{
SqlDataAdapter myCommand = new SqlDataAdapter("select distinct State from Authors", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "States");
MySelect.DataSource= ds.Tables["States"].DefaultView;
MySelect.DataBind();
}
}
public void GetAuthors_Click(Object sender, EventArgs E)
{
String selectCmd = "select * from Authors where state = @State";
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));
myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
MyDataGrid.DataSource= ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
</script>
<body style="font: 10.5pt 宋體">
<form runat="server">
<h3><font face="宋體">對 DataGrid 控件的動態(tài)參數(shù)化選擇</font></h3>
選擇州:
<select id="MySelect" DataTextField="State" runat="server"/>
<input type="submit" OnServerClick="GetAuthors_Click" Value="獲取作者" runat="server"/><p>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="宋體"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/>
</form>
</body>
</html>