DataGrid详解(2)

这例显示可以如何修改使用从 select HtmlControl 传递的值所选择的数据。SqlDataAdapter 维护一个可用于用值替换变量标识符(由名称前的"@"表示)的 Parameters 集合。在该集合中添加一个指定参数的名称、类型和大小的新 SqlParameter,然后将它的 Value 属性设置为选择的值。



在aspx的html代码里加入下面的代码:
<body MS_POSITIONING="GridLayout">
<form runat="server" ID="Form1">
<h3><font face="宋体">对 DataGrid 控件的参数化选择</font></h3>
选择州:
<select id="MySelect" runat="server" NAME="MySelect">
<option selected>CA</option>
<option>IN</option>
<option>KS</option>
<option>MD</option>
<option>MI</option>
<option>OR</option>
<option>TN</option>
<option>UT</option>
</select>
<input type="submit" Value="获取作者" runat="server" ID="Submit1" NAME="Submit1"><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>



在aspx.cs文件里加入下面的代码:
private void Submit1_ServerClick(object sender, System.EventArgs e)
{
string strconn="user id=sa;password=;initial catalog=pubs;data source=jeff";
SqlConnection myConnection = new SqlConnection(strconn);
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, "作者");



MyDataGrid.DataSource= ds.Tables["作者"].DefaultView;
MyDataGrid.DataBind();
}
上一例中静态填充选择框的值,但这不太适合那些值在数据库中会更改的情况。因为 select HtmlControl 也支持 IEnumerable



DataSource 属性,可以转而使用选择查询动态填充选择框,这将保证数据库和用户界面始终同步。下面的示例说明此过程。



<%@ 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 控件的动态参数化选择</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>
前面几个例子学习了从DataBase里面读数据,下面我们学习将数据插入到数据库中,可以向页中添加简单的输入窗体,并在窗体提交事件处理程序中执行插入命令。与前两个示例一样,使用命令对象的 Parameters 集合填充命令的值。注意,在试图插入到数据库中之前,还要检查以确保所需的值非铡U饨乐褂胧菘獾淖侄卧际馔獬逋弧;剐柙?try/catch 块的内部执行插入命令,以防插入行的主键已经存在。



先看aspx文件:
<body MS_POSITIONING="GridLayout">
<form runat="server" ID="Form1">
<h3><font face="宋体">插入具有验证的数据行</font></h3>
<table width="95%">
<tr>
<td valign="top">
<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" />
</td>
<td valign="top">
<table style="FONT: 9pt 宋体">
<tr>
<td colspan="2" bgcolor="#aaaadd" style="FONT:10.5pt 宋体">添加新作者:</td>
</tr>
<tr>
<td nowrap>作者 ID:</td>
<td>
<input type="text" id="au_id" value="000-00-0000" runat="server" NAME="au_id">
<asp:RequiredFieldValidator id="au_idReqVal" ControlToValidate="au_id" Display="Static" Font-Name="Verdana" Font-Size="12" runat="server">&nbsp;*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td nowrap>姓氏:</td>
<td>
<input type="text" id="au_lname" value="Doe" runat="server" NAME="au_lname">
<asp:RequiredFieldValidator id="au_lnameReqVal" ControlToValidate="au_lname" Display="Static" Font-Name="Verdana" Font-Size="12" runat="server">&nbsp;*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td nowrap>名字:</td>
<td>
<input type="text" id="au_fname" value="John" runat="server" NAME="au_fname">
<asp:RequiredFieldValidator id="au_fnameReqVal" ControlToValidate="au_fname" Display="Static" Font-Name="Verdana" Font-Size="12" runat="server">&nbsp;*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>电话:</td>
<td><nobr> <input type="text" id="phone" value="808 555-5555" runat="server" NAME="phone">
<asp:RequiredFieldValidator id="phoneReqVal" ControlToValidate="phone" Display="Static" Font-Name="Verdana" Font-Size="12" runat="server">&nbsp;*</asp:RequiredFieldValidator></nobr>
</td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" id="address" value="One Microsoft Way" runat="server" NAME="address"></td>
</tr>
<tr>
<td>城市:</td>
<td><input type="text" id="city" value="Redmond" runat="server" NAME="city"></td>
</tr>
<tr>
<td>州:</td>
<td>
<select id="state" runat="server" NAME="state">
<option selected>CA</option>
<option>IN</option>
<option>KS</option>
<option>MD</option>
<option>MI</option>
<option>OR</option>
<option>TN</option>
<option>UT</option>
</select>
</td>
</tr>
<tr>
<td nowrap>邮政编码:</td>
<td><input type="text" id="zip" value="98005" runat="server" NAME="zip"></td>
</tr>
<tr>
<td>协定:</td>
<td>
<select id="contract" runat="server" NAME="contract">
<option value="0" selected>假</option>
<option value="1">真</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td style="PADDING-TOP:15px">
<input type="submit" value="添加作者" runat="server" ID="Submit1" NAME="Submit1">
</td>
</tr>
<tr>
<td colspan="2" style="PADDING-TOP:15px" align="middle">
<span id="Message" EnableViewState="false" runat="server">
<asp:RegularExpressionValidator id="RegularExpressionValidator1" ASPClass="RegularExpressionValidator" ControlToValidate="zip" ValidationExpression="[0-9]{5}" Display="Dynamic" Font-Name="Arial" Font-Size="11" runat="server">* 邮政编码必须是 5 位数字<br></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator id="phoneRegexVal" ControlToValidate="phone" ValidationExpression="[0-9]{3} [0-9]{3}-[0-9]{4}" Display="Dynamic" Font-Name="Arial" Font-Size="11" runat="server">* 电话号码格式必须为:XXX XXX-XXXX <br></asp:RegularExpressionValidator> <asp:RegularExpressionValidator id="au_idRegexVal" ControlToValidate="au_id" ValidationExpression="[0-9]{3}-[0-9]{2}-[0-9]{4}" Display="Dynamic" Font-Name="Arial" Font-Size="11" runat="server">* 作者 ID 必须是数字:XXX-XX-XXXX <br></asp:RegularExpressionValidator></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>



aspx.cs文件
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;



namespace study
{
/// <summary>
/// datagrid_5 的摘要说明。
/// </summary>
public class datagrid_5 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid MyDataGrid;
protected System.Web.UI.WebControls.RequiredFieldValidator au_idReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator au_lnameReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator au_fnameReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator phoneReqVal;
protected System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1;
protected System.Web.UI.WebControls.RegularExpressionValidator phoneRegexVal;
protected System.Web.UI.WebControls.RegularExpressionValidator au_idRegexVal;
protected System.Web.UI.HtmlControls.HtmlInputText au_id;
protected System.Web.UI.HtmlControls.HtmlInputText au_lname;
protected System.Web.UI.HtmlControls.HtmlInputText au_fname;
protected System.Web.UI.HtmlControls.HtmlInputText phone;
protected System.Web.UI.HtmlControls.HtmlInputText address;
protected System.Web.UI.HtmlControls.HtmlInputText city;
protected System.Web.UI.HtmlControls.HtmlSelect state;
protected System.Web.UI.HtmlControls.HtmlInputText zip;
protected System.Web.UI.HtmlControls.HtmlSelect contract;
protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
protected System.Web.UI.HtmlControls.HtmlGenericControl Message;
SqlConnection myConnection;
private void Page_Load(object sender, System.EventArgs e)
{
myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");



if (!IsPostBack)
BindGrid();
}



#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Submit1.ServerClick += new System.EventHandler(this.Submit1_ServerClick);
this.Load += new System.EventHandler(this.Page_Load);



}
#endregion



private void Submit1_ServerClick(object sender, System.EventArgs e)
{
Message.InnerHtml = "";



if (Page.IsValid)
{



String insertCmd = "insert into Authors (au_id, au_lname, au_fname, phone, address, city, state, zip, contract) values (@Id, @LName, @FName, @Phone, @Address, @City, @State, @Zip, @Contract)";



SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);



myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar, 11));
myCommand.Parameters["@Id"].Value = au_id.Value;



myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar, 40));
myCommand.Parameters["@LName"].Value = au_lname.Value;



myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar, 20));
myCommand.Parameters["@FName"].Value = au_fname.Value;



myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar, 12));
myCommand.Parameters["@Phone"].Value = phone.Value;



myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));
myCommand.Parameters["@Address"].Value = address.Value;



myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 20));
myCommand.Parameters["@City"].Value = city.Value;



myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar, 2));
myCommand.Parameters["@State"].Value = state.Value;



myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));
myCommand.Parameters["@Zip"].Value = zip.Value;



myCommand.Parameters.Add(new SqlParameter("@Contract", SqlDbType.NVarChar,1));
myCommand.Parameters["@Contract"].Value = contract.Value;



myCommand.Connection.Open();



try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>已添加记录</b><br>" + insertCmd + "<p>";
}
catch (SqlException ex)
{
if (ex.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录<p>";
else
Message.InnerHtml = "错误:未能添加记录,请确保正确填写了字段<p>";
Message.Style["color"] = "red";
}



myCommand.Connection.Close();
}



BindGrid();
}



public void BindGrid()
{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);



DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");



MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
}
}

你可能感兴趣的:(UI,Web,Microsoft,asp.net,asp)