这两天项目中用到了datagrid控件,之前没怎么用过。经过一番努力,最终效果总算是实现了。我有如此感受:
1、功能强大,用法复杂。2、细节很多,应该小心。3、多问多查多试。前台代码如下:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="pinpai_lan_Add.aspx.cs" Inherits="wlgl_spring_pinpai_lan_Add" %> 2 3 4 5 6 7 8 9 10 1142 43
后台代码:
using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;public partial class wlgl_spring_pinpai_lan_Add : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); } } protected void btn_Add_Click(object sender, EventArgs e) { string str=txtLanMu.Text.Trim(); if (str=="") { mess.Text = "必须输入栏目名称!"; return; } DataTable dt = SqlHelper.GetPinpai_lan(); if (dt.Rows.Count>0) { for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["name"].ToString().Trim()==str) { mess.Text = "栏目已存在!"; return; } } } if (SqlHelper.Insert(str)) { mess.Text = "添加栏目成功!"; } else { mess.Text = "添加栏目失败!"; } dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); } protected void dgContents_EditCommand(object source, DataGridCommandEventArgs e) { dgContents.EditItemIndex = e.Item.ItemIndex; dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); } protected void dgContents_CancelCommand(object source, DataGridCommandEventArgs e) { dgContents.EditItemIndex = -1; dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); } protected void dgContents_DeleteCommand(object source, DataGridCommandEventArgs e) { string sid = e.Item.Cells[0].Text; int id; if (int.TryParse(sid, out id)) { if (SqlHelper.DeleteAll(id)) { mess.Text = "删除成功!"; } else { mess.Text = "删除失败!"; } } else { mess.Text = "删除失败!"; } dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); } protected void dgContents_UpdateCommand(object source, DataGridCommandEventArgs e) { string sid =e.Item.Cells[0].Text; int id; string name = ((TextBox)e.Item.Cells[1].Controls[0]).Text; if (int.TryParse(sid,out id)) { if (SqlHelper.Update(id,name)) { mess.Text = "更新成功!"; } else { mess.Text = "更新失败!"; } } else { mess.Text = "更新失败!"; } dgContents.EditItemIndex = -1; dgContents.DataSource = SqlHelper.GetPinpai_lan(); dgContents.DataBind(); }}
我想要的功能是,在datagrid中可以编辑删除数据。