明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

集各種技巧于一身的DataGrid

[摘要]RequiredFieldValidator控件用來(lái)校驗(yàn)一個(gè)輸入框中是否輸入了值,RegularExpressionValidator控件用來(lái)進(jìn)行正則表達(dá)是的匹配。關(guān)于正則表達(dá)式的說明請(qǐng)參閱其他資料. 其中ControlToValidate屬性就是需要校驗(yàn)的文本框的ID號(hào).標(biāo)簽中的文本就是在校驗(yàn)不...

RequiredFieldValidator控件用來(lái)校驗(yàn)一個(gè)輸入框中是否輸入了值,RegularExpressionValidator控件用來(lái)進(jìn)行正則表達(dá)是的匹配。關(guān)于正則表達(dá)式的說明請(qǐng)參閱其他資料.

其中ControlToValidate屬性就是需要校驗(yàn)的文本框的ID號(hào).標(biāo)簽中的文本就是在校驗(yàn)不成功的時(shí)候顯示出來(lái)的提示,Display屬性則是提示信息的顯示方式.

DataGrid中<Columns>標(biāo)簽內(nèi)的內(nèi)容就是DataGrid的列了,列中還可以添加模版列,對(duì)應(yīng)每一模版列,可以有<ItemTemplate>,<EditItemTemplate>,<HeaderTemplate>,<FooterTemplate>幾個(gè)標(biāo)簽,其中<ItemTemplate>就是DataGrid在正常顯示的時(shí)候列的標(biāo)簽了,<EditTemplate>也就是在編輯狀態(tài)中的DataGrid列的樣式了.

在這些標(biāo)簽中我們可以插入控件,然后在后臺(tái)代碼中用DataGrid1.Item[i].FindControls(“Coltrol Name”)可以對(duì)DataGrid中的控件進(jìn)行操作.
為了在DataGeid為編輯狀態(tài)的時(shí)候控制DataGrid包含控件的狀態(tài),我們可以用CSS樣式定義,將下面代碼加入aspx文件的</head>和<Body>中,然后在<asp:TextBox>標(biāo)簽中加入CssClass=“myClass“即可改片控件的樣式。(跟普通的方法沒什么區(qū)別啦,呵呵。)

<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>


這里只給出了部分代碼,如需要完整代碼,請(qǐng)來(lái)信索取。cheaper_c@sina.com

----------------------------------------------------------下面是運(yùn)行時(shí)屏幕接圖-----------------------------------------



------------------------------------------------部分后臺(tái)代碼---------------------------------------------------------

private new void DataBind()

{

DataBind("au_fname");

}

//重載DataBind()方法,方便DataGrid中進(jìn)行排序

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頁(yè)眉上添加全選的CheckBox控件》一文

//原文地址: http://blog.csdn.net/vzxq/archive/2004/09/13/103156.aspx

private void RegClientScript()

{

//對(duì)于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;

}

}

}

//當(dāng)點(diǎn)擊”編輯”按鈕的時(shí)候觸發(fā)的服務(wù)器端函數(shù)

//首先將Panel的Visible屬性設(shè)置為false,因?yàn)楫?dāng)DataGrid在編輯狀態(tài)時(shí)單元格中的控件(如TextBox)會(huì)將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())

{

//這段代碼的作用是對(duì)編輯狀態(tài)中的DataGrid中的控件附值.ddl_table就是前面我們創(chuàng)建的DataTable

ddl_state.SelectedIndex = i;

break;

}

}

}

//取消DataGrid編輯狀態(tài)的時(shí)候觸發(fā)的服務(wù)器端代碼

public void Grid_Cancel(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)

{

Panel1.Visible = true;//將panel顯示出來(lái)

DataGrid1.EditItemIndex = -1;

this.DataBind();

}

//點(diǎn)擊”更新”按鈕是觸發(fā)的函數(shù),更新數(shù)據(jù)庫(kù)中的記錄

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);

}

//分頁(yè)

public void Grid_Page(object sender, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)

{

DataGrid1.EditItemIndex = -1;

Panel1.Visible = true;

DataGrid1.CurrentPageIndex = e.NewPageIndex;

DataBind();

}

//向數(shù)據(jù)庫(kù)中插入記錄

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();

}

----------------------------------------------------------部分前臺(tái)代碼-----------------------------------------------------------------------

<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}">*電話號(hào)碼格式xxx xxx-xxxx</asp:RegularExpressionValidator>

</EditItemTemplate>

</asp:TemplateColumn>

</Columns>

<PagerStyle HorizontalAlign="Center" ForeColor="White" BackColor="#000084" Mode="NumericPages"></PagerStyle>

</asp:datagrid>
(出處:Viphot)