公司要做一个类似于白名单的功能,要求新增时用户点击按钮可以动态的增加或减少GridView的行数。
直接上代码:
首先先创建一个和数据库一样的类:
public class WhiteListConfig { private int strID; public int StrID { get { return strID; } set { strID = value; } } private string strIPType; public string StrIPType { get { return strIPType; } set { strIPType = value; } } private string strIPAddr; public string StrIPAddr { get { return strIPAddr; } set { strIPAddr = value; } } private string strAddDateTime; public string StrAddDateTime { get { return strAddDateTime; } set { strAddDateTime = value; } } private string strMemo; public string StrMemo { get { return strMemo; } set { strMemo = value; } } }
前面页面:
<body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div align="center"> <table width="50%"> <tbody> <tr> <td valign="top" align="center"> <span style="font-size: 14pt; font-family: 宋体"> <br /> <asp:Label ID="LabTrade" runat="server" CssClass="title1">新增白名单</asp:Label> <br /> </span> </td> </tr> <tr> <%--<td style="height: 24px; "> <b>添加白名单</b> <asp:ImageButton ID="btnAddWhite" runat="server" ImageUrl="~/images/add_more.gif" OnClick="btnAddWhite_Click" Style="border-width: 0px;" Text="" /><label for="btnAddWhite" style="color: Blue;" onmouseover="this.style.cursor='hand';this.style.color='orange';" onmouseout="this.style.color='#0000FF';">(点击添加明细)</label> </td>--%> <td style="height: 24px;" align="right"> <%--<span class="btn_2letter" style="display: inline-block;"> <i class="fa fa-plus"></i> <asp:Button ID="btnAddWhite" runat="server" BackColor="Transparent" OnClick="btnAddWhite1_Click" Text="新增" BorderStyle="None" /> </span>--%> <asp:Button ID="btnAddWhite" runat="server" CssClass="btn_2letter" OnClick="btnAddWhite1_Click" Text="新增"/> <asp:Button ID="btnSave" runat="server" CssClass="btn_2letter" Text="保存" OnClick="btnSave_Click" /> </td> </tr> <tr> <td style="padding: 0;"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView ID="GridWhiteList" runat="server" AutoGenerateColumns="False" Style="font-size: 12px;" CssClass="DataGridCtl" Width="100%" BorderStyle="none" CellPadding="0" HeaderStyle-HorizontalAlign="Center" HorizontalAlign="Center" OnRowDataBound="GridWhiteList_RowDataBound"> <Columns> <asp:TemplateField HeaderText="序号"> <ItemTemplate> <%#Container.DataItemIndex + 1%> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> 类型 </HeaderTemplate> <ItemTemplate> <input id="hiddenKey" type="hidden" runat="server" class="hiddenKey" value='<%#Eval("Key")%>' rowindex='<%#Container.DisplayIndex%>' /> <select id="selWeight" runat="server" style="border:solid 1px #ABADB3;width:100px;" rowindex='<%#Container.DisplayIndex%>' > </select> </ItemTemplate> <ItemStyle HorizontalAlign="Center"/> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> IP地址 </HeaderTemplate> <ItemTemplate> <input id="txtIPAddr" style="width:120px" type="text" runat="server" rowindex='<%#Container.DisplayIndex%>' maxlength="20" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> 备注 </HeaderTemplate> <ItemTemplate> <%--<input id="txtMemo" type="text" runat="server" rowindex='<%#Container.DisplayIndex%>' class='<%#"input_short1 Wdate EndTime Enabled" + Container.DisplayIndex%>' />--%> <textarea id="textMemo" runat="server" onkeyup="checkWordCount(this);" rowindex='<%#Container.DisplayIndex%>' style="width:300px;"></textarea> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="删除"> <HeaderStyle HorizontalAlign="Center" /> <ItemTemplate> <asp:ImageButton ID="ListDel" runat="server" ImageUrl="../images/del.gif" CommandName='<%#Bind("Key")%>' OnClick="btnDeleteWhite_Click" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> <EmptyDataTemplate> <table class="HeaderCss" cellspacing="0" rules="all" id="Table2" style="border-collapse: collapse;"> <tr style="background-color: #E5F0F2;"> <th scope="col" align="center"> 序号 </th> <th scope="col" align="center"> 类型 </th> <th scope="col" align="center"> IP地址 </th> <th scope="col" align="center" > 备注 </th> <th scope="col" align="center"> 删除 </th> </tr> </table> </EmptyDataTemplate> <RowStyle BackColor="White" /> <EditRowStyle BorderStyle="None" /> <HeaderStyle BorderStyle="None" CssClass="HeaderCss" BackColor="#E5F0F2" HorizontalAlign="Center" /> <PagerStyle BackColor="#E7E7E7" ForeColor="Black" HorizontalAlign="Center" Height="10px" /> </asp:GridView> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnAddWhite" EventName="Click<span style="font-family: Arial, Helvetica, sans-serif;">" /></span> </Triggers> </asp:UpdatePanel> </td> </tr> </tbody> </table> </div> </form> </body>后台c#代码:
public partial class CSPZ_WhiteListAdd : System.Web.UI.Page { IBusinessQuery newIBusQuery = BusinessFactory.CreateDataQuery();//取数据的接口 protected DataTable WhiteDT { get { DataTable dt = ViewState["WhiteDT"] as DataTable; if (dt == null) { ViewState["WhiteDT"] = dt = new DataTable(); dt.Columns.Add("IPType", typeof(string)); dt.Columns.Add("IPAddr", typeof(string)); dt.Columns.Add("AddDateTime", typeof(string)); dt.Columns.Add("Memo", typeof(string)); dt.PrimaryKey = new DataColumn[] { dt.Columns.Add("Key") }; } return dt; } } protected List<WhiteListConfig> WhiteList { get { List<WhiteListConfig> wList = new List<WhiteListConfig>(); DataTable dt = this.WhiteDT; if (dt.Rows.Count > 0) { WhiteListConfig w = null; foreach (DataRow row in dt.Rows) { w = new WhiteListConfig(); w.StrIPType = row["IPType"].ToString(); w.StrIPAddr = row["IPAddr"].ToString(); w.StrAddDateTime = row["AddDateTime"].ToString(); w.StrMemo = row["Memo"].ToString(); wList.Add(w); } } return wList; } set { List<WhiteListConfig> wList = value; DataTable dt = this.WhiteDT; if (dt.Rows.Count > 0) { dt.Rows.Clear(); } if (wList != null && wList.Count > 0) { DataRow row = null; foreach (WhiteListConfig w in wList) { row = dt.NewRow(); row["Key"] = Guid.NewGuid().ToString(); row["IPType"] = w.StrIPType; row["IPAddr"] = w.StrIPAddr; row["AddDateTime"] = w.StrAddDateTime.ToString(); row["Memo"] = w.StrMemo; dt.Rows.Add(row); } } } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataRow row = WhiteDT.NewRow(); row["Key"] = Guid.NewGuid().ToString(); WhiteDT.Rows.Add(row); GridWhiteList.DataSource = WhiteDT; GridWhiteList.DataBind(); } } protected void btnAddWhite1_Click(object sender, EventArgs e) { for (int i = 0; i < GridWhiteList.Rows.Count; i++) { HtmlSelect hs = GridWhiteList.Rows[i].Cells[1].FindControl("selWeight") as HtmlSelect; string strIPType = hs.Value; WhiteDT.Rows[i]["IPType"] = strIPType; HtmlInputText hit = GridWhiteList.Rows[i].Cells[2].FindControl("txtIPAddr") as HtmlInputText; string strIPAddr = hit.Value; if (!string.IsNullOrEmpty(strIPAddr)) { if (Regex.IsMatch(strIPAddr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$") == false) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">alert('IP地址不正确!')</script>"), false); return; } else { WhiteDT.Rows[i]["IPAddr"] = strIPAddr; } } else { ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">alert('IP地址不能为空!')</script>"), false); return; } WhiteDT.Rows[i]["AddDateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); HtmlTextArea hta = GridWhiteList.Rows[i].Cells[3].FindControl("textMemo") as HtmlTextArea; string strMemo = hta.Value; WhiteDT.Rows[i]["Memo"] = strMemo; } for (int i = 0; i < WhiteDT.Rows.Count; i++) { for (int j = 0; j < WhiteDT.Rows.Count; j++) { if (i == j) continue; else { if (WhiteDT.Rows[i]["IPType"].ToString() == WhiteDT.Rows[j]["IPType"].ToString() && WhiteDT.Rows[i]["IPAddr"].ToString() == WhiteDT.Rows[j]["IPAddr"].ToString()) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">alert('IP地址重复!')</script>"), false); return; } } } } DataRow row = WhiteDT.NewRow(); row["Key"] = Guid.NewGuid().ToString(); WhiteDT.Rows.Add(row); GridWhiteList.DataSource = WhiteDT; GridWhiteList.DataBind(); ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">{0}</script>", "SetTimeControl();"), false); } protected void btnDeleteWhite_Click(object sender, ImageClickEventArgs e) { string StrKey = ((ImageButton)sender).CommandName; if (String.IsNullOrEmpty(StrKey)) { return; } DataRow selectedRow = WhiteDT.Rows.Find(StrKey); if (selectedRow != null) { if (GridWhiteList.Rows.Count == 1) { ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">alert('不允许删除!')</script>"), false); return; } WhiteDT.Rows.Remove(selectedRow); GridWhiteList.DataSource = WhiteDT; GridWhiteList.DataBind(); } ScriptManager.RegisterStartupScript(this, this.GetType(), "Msg", String.Format("<script type=\"text/javascript\" language=\"javascript\">{0}</script>", "SetTimeControl();"), false); } protected void GridWhiteList_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HtmlSelect selWeight = e.Row.FindControl("selWeight") as HtmlSelect; ListItem tmpItem = null; tmpItem = new ListItem(); tmpItem.Text = "源地址"; tmpItem.Value = "源地址"; selWeight.Items.Add(tmpItem); tmpItem = new ListItem(); tmpItem.Text = "目标地址"; tmpItem.Value = "目标地址"; selWeight.Items.Add(tmpItem); if (DataBinder.Eval(e.Row.DataItem, "IPType").ToString() == "源地址") { ((HtmlSelect)e.Row.FindControl("selWeight")).SelectedIndex = 0; } else if (DataBinder.Eval(e.Row.DataItem, "IPType").ToString() == "目标地址") { ((HtmlSelect)e.Row.FindControl("selWeight")).SelectedIndex = 1; } ((HtmlInputText)e.Row.FindControl("txtIPAddr")).Value = DataBinder.Eval(e.Row.DataItem, "IPAddr").ToString(); ((HtmlTextArea)e.Row.FindControl("textMemo")).Value = DataBinder.Eval(e.Row.DataItem, "Memo").ToString(); } } protected void btnSave_Click(object sender, EventArgs e) { DataTable dt = WhiteDT.Clone(); dt.PrimaryKey = null; dt.Columns.Remove("Key"); if (GridWhiteList.Rows.Count == 0) { Response.Write("<script>alert('请输入至少一条数据!');</script>"); return; } for (int i = 0; i < GridWhiteList.Rows.Count; i++) { DataRow dr = dt.NewRow(); HtmlSelect hs = GridWhiteList.Rows[i].Cells[1].FindControl("selWeight") as HtmlSelect; string strIPType = hs.Value; dr["IPType"] = strIPType; HtmlInputText hit = GridWhiteList.Rows[i].Cells[2].FindControl("txtIPAddr") as HtmlInputText; string strIPAddr = hit.Value; if (!string.IsNullOrEmpty(strIPAddr)) { if (Regex.IsMatch(strIPAddr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$") == false) { Response.Write("<script>alert('IP地址不正确!')</script>"); return; } else { dr["IPAddr"] = strIPAddr; } } else { Response.Write("<script>alert('IP地址不能为空!')</script>"); return; } dr["AddDateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); HtmlTextArea hta = GridWhiteList.Rows[i].Cells[3].FindControl("textMemo") as HtmlTextArea; string strMemo = hta.Value; dr["Memo"] = strMemo; dt.Rows.Add(dr); } DataTable dtWhite = newIBusQuery.GetWhiteListConfig("", ""); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dtWhite.Rows.Count; j++) { if (dt.Rows[i]["IPAddr"].ToString() == dtWhite.Rows[j]["IPAddr"].ToString() && dt.Rows[i]["IPType"].ToString() == dtWhite.Rows[j]["IPType"].ToString()) { Response.Write("<script>alert('第" + (i + 1) + "条数据已存在!');</script>"); return; } } } IPWhiteListConfig iw = new IPWhiteListConfig(); dt.TableName = "T_WhiteListConfig"; iw.AddWhiteIP(dt); Response.Write("<script>alert('保存成功!');</script>"); Page.RegisterStartupScript("", "<script>window.opener.location.href = window.opener.location.href;window.close();</script>"); } }