Gridview行编辑,备份一下
一年前因为项目需要碰到了大量行编辑的表单~~!,写过一次gridview的行编辑。今天又碰到这个问题~~!
看了下网上的写法大多数都是通过findcontrol的方法实现的,我也没想到好的办法,就简单的封装了一下。写的不好见谅~~!
同事帮改成多表模式的了。现在拿出来看看感觉累赘了。。
先说说功能支持gridview增加行删除行,保持gridview中已存在的数据。
保存数据的处理方法写的不太好,想改进一下,但是没时间搞,先贴出来备份一下吧。欢迎指点。
在gridview中配置DataFields(即要绑定到gridview的字段,也是后台构建临时dt的字段名)
通过FooterTemplate中的添加按钮来执行添加,相应的事件在下面
主要是为绑定的空间增加DataField 自定义属性,这样可以根据需要进行扩展。
但是现在用起来感觉配置起来有些麻烦呵呵。如果不是大量表单使用行编辑,不推荐使用
这个方法主要是可以把编辑下的gridview直接反向成dt,然后根据需要进行操作。
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="gvList1" runat="server" AutoGenerateColumns="False" CssClass="grid_bd" EmptyDataText="没有记录。" Width="100%" ShowFooter="True" DataFields="SampleID,SampleFolderID,SampleType,SampleCode,PointID,PointName,SampleTime,Temp, Smell, WaterColor,Eutrophication, remark,PointCategory,CheckItems,CheckItemsID" OnRowDataBound="gvList1_RowDataBound" OnRowDeleting="gvList1_RowDeleting"> <RowStyle CssClass="gridItem" /> <HeaderStyle CssClass="gridHeader" /> <EmptyDataRowStyle CssClass="gridEmpty" /> <Columns> <asp:TemplateField HeaderText="序号"> <HeaderStyle CssClass="gd_center" /> <ItemStyle HorizontalAlign="Center"></ItemStyle> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("SampleID") %>' Style="display: none;"></asp:Label> <asp:Label ID="lb_senquens" runat="server" Text=''></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="测点位置"> <HeaderStyle CssClass="gd_center" /> <ItemStyle HorizontalAlign="Center"></ItemStyle> <ItemTemplate> ***省略业务数据 <asp:TemplateField HeaderText="备注" Visible="false"> <ItemTemplate> <asp:TextBox ID="txtRemark" runat="server" Width="80px" TBName="T_Bas_Sample" Text='<%# Bind("remark") %>' Msg="备注" DataField="remark" IsNull="True" FieldType="string"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="删除" ItemStyle-HorizontalAlign="Center"> <HeaderStyle CssClass="gd_center" /> <ItemStyle HorizontalAlign="Center"></ItemStyle> <FooterStyle CssClass="gd_center" /> <ItemTemplate> <asp:ImageButton ID="DeleteLink0" runat="server" CommandName="delete" ImageUrl="../_Images/btn/del.gif" isshow="false" /> </ItemTemplate> <FooterTemplate> <asp:Button ID="Btn_add11" Text="添加" runat="server" OnClick="Btn_add21_Click" isshow="false" /> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel>
事件
添加
删除
删除
protected void gvList1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int i = e.RowIndex;
DataTable dtTmp = Common.GetDataTableByGridView(this.gvList1);
if (i > 0 && i < dtTmp.Rows.Count)//保留一个空行
dtTmp.Rows.RemoveAt(i);
this.gvList1.DataSource = dtTmp;
this.gvList1.DataBind();
}
封装部分
封装部分
/// <summary>
/// 编辑
/// </summary>
/// <param name="gv"></param>
/// <returns></returns>
public static DataTable GetDataTableByGridView(GridView gv)
{
return GetDataTableByGridView(gv, "", null);
}
/// <summary>
/// 根据GridView获取DataTable
/// </summary>
/// <param name="gv"></param>
/// <param name="keyField">主键字段名,通过该字段清除无效记录</param>
/// <param name="fieldValues">需要遍历指定字段值的字典</param>
/// <returns></returns>
public static DataTable GetDataTableByGridView(GridView gv, string keyField)
{
return GetDataTableByGridView(gv, keyField, null);
}
/// <summary>
/// 根据GridView获取DataTable
/// </summary>
/// <param name="gv"></param>
/// <param name="keyField">主键字段名,通过该字段清除无效记录</param>
/// <param name="fieldValues">需要遍历指定字段值的字典,主要用于关联字段</param>
/// <returns></returns>
public static DataTable GetDataTableByGridView(GridView gv, string keyField, Dictionary<string, string> fieldValues)
{
return GetDataTableByGridView(gv, null, keyField, fieldValues);
}
/// <summary>
/// 根据GridView获取DataTable
/// </summary>
/// <param name="gv"></param>
/// <param name="keyField">主键字段名,通过该字段清除无效记录</param>
/// <param name="fieldValues">需要遍历指定字段值的字典,主要用于关联字段</param>
/// <returns></returns>
public static DataTable GetDataTableByGridView(GridView gv, string tableName, string keyField, Dictionary<string, string> fieldValues)
{
DataTable dt = new DataTable();
TextBox tmpTxtbox = new TextBox();
int iColumnCount = gv.Columns.Count;//列数
if (!gv.ShowHeader && gv.Columns.Count == 0)
{
return dt;
}
GridViewRow headerRow = gv.HeaderRow;
int columnCount = headerRow.Cells.Count;
//创建列
if (!string.IsNullOrEmpty(gv.Attributes["DataFields"]))
{
string[] arrTmp = gv.Attributes["DataFields"].Split(',');
string[] valueAndType;
foreach (string s in arrTmp)
{
valueAndType = s.Split('|');
Type theType = GetFieldType(valueAndType);
dt.Columns.Add(valueAndType[0].Trim(), theType);
}
//新增不存在的关联字段
if (fieldValues != null)
{
foreach (KeyValuePair<string, string> entry in fieldValues)
{
if (dt.Columns.IndexOf(entry.Key) == -1 && dt.Columns.IndexOf(entry.Key.ToLower()) == -1)
{
dt.Columns.Add(entry.Key, typeof(string));
}
}
}
}
//追加textbox中的记录
// string strTxtTmp = "";
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
DataRow drTmp = dt.NewRow();
for (int i = 0; i < iColumnCount; i++)
{
//遍历所有列
SetFieldValue(dt, drTmp, gvr.Cells[i]);
}
dt.Rows.Add(drTmp);
}
}
//给关联字段赋值
if (fieldValues != null)
{
foreach (KeyValuePair<string, string> entry in fieldValues)
{
if (dt.Columns.Contains(entry.Key))
{
foreach (DataRow dr in dt.Rows)
{
dr[entry.Key] = entry.Value;
}
}
}
}
//清除空记录
if (!string.IsNullOrEmpty(keyField))
{
if (dt.Columns.Contains(keyField))
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
if (dr[keyField].ToString().Length > 0)
{
}
else
{
dt.Rows.Remove(dr);
i--;
}
}
}
else
{
new Exception("指定的字段不存在,字段名为:" + keyField);
}
}
return dt;
}
public static void SetFieldValue(DataTable dt, DataRow drTmp, TableCell tcell)
{
string strField = "";
string strFieldTyp = "";
string text = tcell.Text;
TextBox txTmp = new TextBox();
Label lbTmp = new Label();
if (!string.IsNullOrEmpty(text))
{
strField = tcell.Attributes["DataField"];
if (!string.IsNullOrEmpty(strField))
{
if (dt.Columns.Contains(tcell.Attributes["DataField"]))
{
drTmp[strField] = text;
}
}
}
foreach (Control control in tcell.Controls)
{
if (control != null && control is TextBox)
{
txTmp = (TextBox)control;
strField = txTmp.Attributes["DataField"];
strFieldTyp = txTmp.Attributes["FieldType"];
if (!string.IsNullOrEmpty(strField))
{
if (dt.Columns.Contains(strField))
{
if (GetFieldType(strFieldTyp) == typeof(decimal))
{
if (txTmp.Text == "")
{
//drTmp[strField] = DBNull.Value;
}
else
{
drTmp[strField] = txTmp.Text;
}
}
else if (GetFieldType(strFieldTyp) == typeof(DateTime))
{
if (txTmp.Text == "")
{
drTmp[strField] = DBNull.Value;
}
else
{
drTmp[strField] = txTmp.Text;
}
}
else
{
drTmp[strField] = txTmp.Text;
}
//break;
}
}
}
else if (control != null && control is Label)
{
lbTmp = (Label)control;
strField = lbTmp.Attributes["DataField"];
if (!string.IsNullOrEmpty(strField))
{
if (dt.Columns.Contains(strField))
{
drTmp[strField] = lbTmp.Text;
//break;
}
}
}
else if (control != null && control is DropDownList)
{
DropDownList ddl = (DropDownList)control;
strField = ddl.Attributes["DataField"];
string strTextField = ddl.Attributes["DataDispalyField"];//DropDownList的文本存储字段
if (!string.IsNullOrEmpty(strField))
{
if (dt.Columns.Contains(strField))
{
drTmp[strField] = ddl.SelectedValue;
//break;
}
////DropDownList的文本存储字段处理
if (!string.IsNullOrEmpty(strTextField))
{
if (dt.Columns.Contains(strTextField))
{
if (ddl.SelectedItem != null)
{
drTmp[strTextField] = ddl.SelectedItem.Text;
//break;
}
}
}
}
}
else if (control != null && control is RadioButtonList)
{
RadioButtonList rbl = (RadioButtonList)control;
strField = rbl.Attributes["DataField"];
string strTextField = rbl.Attributes["DataDispalyField"];//DropDownList的文本存储字段
if (!string.IsNullOrEmpty(strField))
{
if (dt.Columns.Contains(strField))
{
drTmp[strField] = rbl.SelectedValue;
//break;
}
////DropDownList的文本存储字段处理
if (!string.IsNullOrEmpty(strTextField))
{
if (dt.Columns.Contains(strTextField))
{
if (rbl.SelectedItem != null)
{
drTmp[strTextField] = rbl.SelectedItem.Text;
//break;
}
}
}
}
}
}
}
public static string GetCellText(TableCell cell)
{
string text = cell.Text;
if (!string.IsNullOrEmpty(text))
{
return text;
}
foreach (Control control in cell.Controls)
{
if (control != null && control is IButtonControl)
{
IButtonControl btn = control as IButtonControl;
text = btn.Text.Replace("\r\n", "").Trim();
break;
}
if (control != null && control is ITextControl)
{
LiteralControl lc = control as LiteralControl;
if (lc != null)
{
continue;
}
ITextControl l = control as ITextControl;
text = l.Text.Replace("\r\n", "").Trim();
break;
}
}
return text;
}
private static Type GetFieldType(string[] valueAndType)
{
Type t;
if (valueAndType.Length > 1)
{
t = GetFieldType(valueAndType[1]);
}
else
{
t = typeof(string);
}
return t;
}
private static Type GetFieldType(string Field)
{
Type type = typeof(string);
switch (Field.ToLower())
{
case "string":
type = typeof(string);
break;
case "int":
type = typeof(Int32);
break;
case "decimal":
type = typeof(decimal);
break;
case "char":
type = typeof(string);
break;
case "datetime":
type = typeof(DateTime);
break;
case "time":
type = typeof(DateTime);
break;
case "date":
type = typeof(DateTime);
break;
case "text":
type = typeof(string);
break;
default:
type = typeof(string);
break;
}
return type;
}
代码
protected void Btn_add21_Click(object sender, EventArgs e)
{
DataTable dtTmp = Common.GetDataTableByGridView(this.gvList1);
dtTmp.Rows.Add(dtTmp.NewRow());
this.gvList1.DataSource = dtTmp;
this.gvList1.DataBind();
}