集各种技巧于一身的DataGrid
发表时间:2024-01-22 来源:明辉站整理相关软件相关文章人气:
[摘要]RequiredFieldValidator控件用来校验一个输入框中是否输入了值,RegularExpressionValidator控件用来进行正则表达是的匹配。关于正则表达式的说明请参阅其他资料. 其中ControlToValidate属性就是需要校验的文本框的ID号.标签中的文本就是在校验不...
RequiredFieldValidator控件用来校验一个输入框中是否输入了值,RegularExpressionValidator控件用来进行正则表达是的匹配。关于正则表达式的说明请参阅其他资料.
其中ControlToValidate属性就是需要校验的文本框的ID号.标签中的文本就是在校验不成功的时候显示出来的提示,Display属性则是提示信息的显示方式.
DataGrid中<Columns>标签内的内容就是DataGrid的列了,列中还可以添加模版列,对应每一模版列,可以有<ItemTemplate>,<EditItemTemplate>,<HeaderTemplate>,<FooterTemplate>几个标签,其中<ItemTemplate>就是DataGrid在正常显示的时候列的标签了,<EditTemplate>也就是在编辑状态中的DataGrid列的样式了.
在这些标签中我们可以插入控件,然后在后台代码中用DataGrid1.Item[i].FindControls(“Coltrol Name”)可以对DataGrid中的控件进行操作.
为了在DataGeid为编辑状态的时候控制DataGrid包含控件的状态,我们可以用CSS样式定义,将下面代码加入aspx文件的</head>和<Body>中,然后在<asp:TextBox>标签中加入CssClass=“myClass“即可改片控件的样式。(跟普通的方法没什么区别啦,呵呵。)
<style type="text/css">.myTextBox { BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; FONT-SIZE: 9pt; BORDER-LEFT: #000000 1px solid; WIDTH: 80px; BORDER-BOTTOM: #000000 1px solid; HEIGHT: 20px }
</style>
这里只给出了部分代码,如需要完整代码,请来信索取。cheaper_c@sina.com
----------------------------------------------------------下面是运行时屏幕接图-----------------------------------------
------------------------------------------------部分后台代码---------------------------------------------------------
private new void DataBind()
{
DataBind("au_fname");
}
//重载DataBind()方法,方便DataGrid中进行排序
private void DataBind(string sortfield)
{
ds = new DataSet();
da = new SqlDataAdapter("SELECT * FROM authors_new",conn);
da.Fill(ds,"authors");
DataView source = ds.Tables["authors"].DefaultView;
source.Sort = sortfield;
DataGrid1.DataSource = source;
DataGrid1.DataBind();
SqlDataAdapter ddl_da = new SqlDataAdapter("SELECT DISTINCT state FROM authors_new",conn);
ddl_da.Fill(ddl_table);
RegClientScript();
}
//这段方法参照了vzxq兄的《在DataGrid页眉上添加全选的CheckBox控件》一文
//原文地址: http://blog.csdn.net/vzxq/archive/2004/09/13/103156.aspx
private void RegClientScript()
{
//对于DataGrid1.Controls[0],大家可以参看vzxq兄的另一篇文章
//http://blog.csdn.net/vzxq/archive/2004/09/13/103167.aspx
foreach (DataGridItem item in DataGrid1.Controls[0].Controls)
{
if (item.ItemType == ListItemType.Header)
{
CheckBox chkAll=(CheckBox)item.FindControl("ChkAll");
System.Text.StringBuilder strScript = new System.Text.StringBuilder("<script language='javascript'> \n");
strScript.Append(" function checkStatus() { \n");
strScript.Append(" var bAll = true; \n");
strScript.Append(" bAll = document.all('" + chkAll.ClientID + "').checked; \n");
for(int i=0; i<DataGrid1.Items.Count ; i++)
{
strScript.Append(" document.all('" + DataGrid1.Items[i].Cells[0].FindControl("CheckBox1").ClientID + "').checked = bAll; \n");
}
strScript.Append(" } \n");
strScript.Append("</script> \n");
if(!Page.IsClientScriptBlockRegistered("checkStatus"))
Page.RegisterClientScriptBlock("checkStatus",strScript.ToString());
chkAll.Attributes.Add("onclick","checkStatus()");
break;
}
}
}
//当点击”编辑”按钮的时候触发的服务器端函数
//首先将Panel的Visible属性设置为false,因为当DataGrid在编辑状态时单元格中的控件(如TextBox)会将DataGeid撑宽
//挤到我们添加记录的panel就不好看了.
public void Grid_Edit(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
Panel1.Visible = false;
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
DataBind();
System.Web.UI.WebControls.DropDownList ddl_state = (DropDownList)DataGrid1.Items[(int)e.Item.ItemIndex].FindControl("edit_state");
ddl_state.DataSource = ddl_table.DefaultView;
ddl_state.DataTextField = "state";
ddl_state.DataBind();
for(int i=0;i<ddl_table.Rows.Count;i++)
{
if(((Label)e.Item.FindControl("lbl_state")).Text==ddl_table.Rows[i][0].ToString())
{
//这段代码的作用是对编辑状态中的DataGrid中的控件附值.ddl_table就是前面我们创建的DataTable
ddl_state.SelectedIndex = i;
break;
}
}
}
//取消DataGrid编辑状态的时候触发的服务器端代码
public void Grid_Cancel(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
Panel1.Visible = true;//将panel显示出来
DataGrid1.EditItemIndex = -1;
this.DataBind();
}
//点击”更新”按钮是触发的函数,更新数据库中的记录
public void Grid_Update(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
int pageindex = DataGrid1.CurrentPageIndex;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE authors_new SET au_id=@au_id, au_lname=@au_lname, au_fname=@au_fname, phone=@phone, address=@address, state=@state, zip=@zip, city=@city, contract=@contract WHERE au_id = @au_id";
cmd.Parameters.Add(new SqlParameter("@au_id",SqlDbType.VarChar,11));
cmd.Parameters["@au_id"].Value = e.Item.Cells[1].Text;
cmd.Parameters.Add(new SqlParameter("@au_lname",SqlDbType.VarChar,40));
cmd.Parameters["@au_lname"].Value = ((TextBox)e.Item.FindControl("edit_lname")).Text;
cmd.Parameters.Add(new SqlParameter("@au_fname",SqlDbType.VarChar,20));
cmd.Parameters["@au_fname"].Value = ((TextBox)e.Item.FindControl("edit_fname")).Text;
cmd.Parameters.Add(new SqlParameter("@phone",SqlDbType.Char,12));
cmd.Parameters["@phone"].Value = ((TextBox)e.Item.FindControl("edit_phone")).Text;
cmd.Parameters.Add(new SqlParameter("@address",SqlDbType.VarChar,40));
cmd.Parameters["@address"].Value = ((TextBox)e.Item.FindControl("edit_address")).Text;
cmd.Parameters.Add(new SqlParameter("@state",SqlDbType.VarChar,40));
cmd.Parameters["@state"].Value = ((DropDownList)e.Item.FindControl("edit_state")).SelectedItem.Value;
cmd.Parameters.Add(new SqlParameter("@zip",SqlDbType.Char,5));
cmd.Parameters["@zip"].Value = ((TextBox)e.Item.FindControl("edit_zip")).Text;
cmd.Parameters.Add(new SqlParameter("@city",SqlDbType.VarChar,20));
cmd.Parameters["@city"].Value = ((TextBox)e.Item.FindControl("edit_city")).Text;
cmd.Parameters.Add(new SqlParameter("@contract",SqlDbType.Char,1));
if(((CheckBox)e.Item.FindControl("edit_contract")).Checked)
{
cmd.Parameters["@contract"].Value = "1";
}
else
{
cmd.Parameters["@contract"].Value = "0";
}
cmd.Connection = conn;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Label1.Text = ex.Message.ToString();
}
finally
{
cmd.Dispose();
}
DataGrid1.EditItemIndex = -1;
DataBind();
Panel1.Visible = true;
DataGrid1.CurrentPageIndex = pageindex;
}
//排序
public void Grid_Sort(object sender, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
DataBind(e.SortExpression);
}
//分页
public void Grid_Page(object sender, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
DataGrid1.EditItemIndex = -1;
Panel1.Visible = true;
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataBind();
}
//向数据库中插入记录
private void Button2_Click(object sender, System.EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText= "INSERT INTO authors_new (au_id, au_lname, au_fname, phone, address, state, zip, city, contract) VALUES (@au_id, @au_lname, @au_fname, @phone, @address, @state, @zip, @city, @contract)";
cmd.Parameters.Add(new SqlParameter("@au_id",SqlDbType.VarChar,11));
cmd.Parameters["@au_id"].Value = txt_id.Text;
cmd.Parameters.Add(new SqlParameter("@au_lname",SqlDbType.VarChar,40));
cmd.Parameters["@au_lname"].Value = txt_lname.Text;
cmd.Parameters.Add(new SqlParameter("@au_fname",SqlDbType.VarChar,20));
cmd.Parameters["@au_fname"].Value = txt_fname.Text;
cmd.Parameters.Add(new SqlParameter("@phone",SqlDbType.Char,12));
cmd.Parameters["@phone"].Value = txt_phone.Text;
cmd.Parameters.Add(new SqlParameter("@address",SqlDbType.VarChar,40));
cmd.Parameters["@address"].Value = txt_address.Text;
cmd.Parameters.Add(new SqlParameter("@state",SqlDbType.VarChar,40));
cmd.Parameters["@state"].Value = txt_state.Text;
cmd.Parameters.Add(new SqlParameter("@zip",SqlDbType.Char,5));
cmd.Parameters["@zip"].Value = txt_zip.Text;
cmd.Parameters.Add(new SqlParameter("@city",SqlDbType.VarChar,20));
cmd.Parameters["@city"].Value = txt_city.Text;
cmd.Parameters.Add(new SqlParameter("@contract",SqlDbType.Char,1));
if(chk_contract.Checked)
{
cmd.Parameters["@contract"].Value = "1";
}
else
{
cmd.Parameters["@contract"].Value = "0";
}
cmd.Connection = conn;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Label1.Text = ex.Message.ToString();
}
finally
{
cmd.Dispose();
}
DataBind();
}
----------------------------------------------------------部分前台代码-----------------------------------------------------------------------
<asp:datagrid id="DataGrid1" OnEditCommand="Grid_Edit" OnCancelCommand="Grid_Cancel" OnUpdateCommand="Grid_Update" AutoGenerateColumns="False" AllowSorting="True" OnPageIndexChanged="Grid_Page" OnSortCommand="Grid_Sort" AllowPaging="True">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="ChkAll" Runat="server"></asp:CheckBox>全选
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn Visible="False" DataField="au_id" ReadOnly="True"></asp:BoundColumn>
<asp:TemplateColumn SortExpression="phone" HeaderText="电话">
<ItemTemplate>
<asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"phone")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox CssClass="myTextBox" Runat="server" ID="edit_phone" Text='<%# DataBinder.Eval(Container.DataItem, "phone")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="phonereqval" Runat="server" ControlToValidate="edit_phone" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="phoneregval" Runat="server" ControlToValidate="edit_phone" Display="Dynamic"
ValidationExpression="[0-9]{3} [0-9]{3}-[0-9]{4}">*电话号码格式xxx xxx-xxxx</asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Center" ForeColor="White" BackColor="#000084" Mode="NumericPages"></PagerStyle>
</asp:datagrid>
(出处:Viphot)