假如我将数据库的字段名放在对应控件的ID属性里,求控件值保存及显示的公用程序! 比如我把字段名放在(textbox/dropdownlist/checkbox/radiobutton....)的ID属性里,保存时自动把控件的值放到ID对应的字段名里。显示也是同样道理。 求公用的显示及保存程序。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 实在是看不明白.我想看过此贴的人已经有N多了,你还是用规范一点的作法吧.另外,textbox和dropdownlist的表现方式本来就不一样.根本无法有公用的程序. using System;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Collections;using System.Data.SqlClient;namespace TimeSpaceInfo.UI{ /// <summary> /// 读取或获取WebForm上的数据 /// </summary> public class UIAccesser { public delegate string FormatDateTimeHandler(DateTime Time,string FieldName); public UIAccesser() { } #region DisplayRowDataUponWebDoc /// <summary> ///将MyRow的数据按照名称匹配的方式写入ctrl的元素里 /// </summary> public static bool DisplayRowDataUponWebDoc(Control ctrl,DataRow MyRow,FormatDateTimeHandler DateTimeHandler) { DataTable MyTable = MyRow.Table; //foreach( Control con in ctrl.Controls) for(int x=0;x<MyTable.Columns.Count;x++) { #region 获取Row值 和页面上的控件 Control con = ctrl.FindControl(MyTable.Columns[x].ColumnName); if(con == null) continue; string CtrlName= con.ID; if( (CtrlName == null) || (CtrlName == "")) continue; //if(!( MyTable.Columns.IndexOf(CtrlName) >=0 )) continue; Type CtrlType = con.GetType(); #endregion #region 根据类型加载数据到页面 if(CtrlType == typeof(Label)) { #region 标签 ((Label)con).Text = MyRow[CtrlName].ToString(); #endregion continue; } if(CtrlType == typeof(TextBox)) { #region 文本框 if(MyTable.Columns[x].DataType== typeof(DateTime)) //日期处理方法 { if(DateTimeHandler!= null) { if(MyRow[CtrlName] != DBNull.Value) ((TextBox)con).Text = DateTimeHandler((DateTime)MyRow[CtrlName],CtrlName); } else { //默认精确到天 string s = MyRow[CtrlName].ToString(); int p = s.IndexOf(" "); ((TextBox)con).Text = p>=0 ?s.Substring(0,p):s; } } else ((TextBox)con).Text = MyRow[CtrlName].ToString(); #endregion continue; } if(CtrlType == typeof(DropDownList)) { #region 下拉框 DropDownList DL = (DropDownList)con; DL.SelectedIndex = -1; ListItem LI = DL.Items.FindByValue(MyRow[CtrlName].ToString()); if(LI!=null) DL.SelectedIndex = DL.Items.IndexOf(LI); else DL.SelectedIndex = DL.Items.IndexOf( DL.Items.FindByText(MyRow[CtrlName].ToString()) ); #endregion continue; } if(CtrlType == typeof(CheckBox)) { #region 单选框 if(MyRow[CtrlName] != DBNull.Value) ((CheckBox)con).Checked = Convert.ToBoolean( MyRow[CtrlName] ); #endregion continue; } if(CtrlType == typeof(Image)) { #region 图片域 ((System.Web.UI.WebControls.Image) con).ImageUrl = MyRow[CtrlName].ToString(); #endregion continue; } if(CtrlType == typeof(RadioButtonList)) { #region 多选一 RadioButtonList list = con as RadioButtonList; list.SelectedIndex = -1; string Value=MyRow[CtrlName].ToString(); ListItem item = list.Items.FindByValue(Value); if(item != null) { list.SelectedIndex = list.Items.IndexOf(item); } else { item = list.Items.FindByText(Value); if(item != null) list.SelectedIndex = list.Items.IndexOf(item); } #endregion continue; } if(CtrlType == typeof(CheckBoxList)) { #region 多选多 选项之间用","隔开 CheckBoxList list = con as CheckBoxList; string []Values = MyRow[CtrlName].ToString().Split(','); foreach(ListItem item in list.Items) item.Selected = false; foreach(ListItem item in list.Items) { foreach(string v in Values) { if(item.Value == v) { item.Selected = true; break; } } } #endregion continue; } #endregion } return true; } /// <summary> /// 将MyRow的数据按照名称匹配的方式写入CtrlFormatString的元素里 /// </summary> /// <param name="ctrl"></param> /// <param name="MyRow"></param> /// <param name="DateTimeHandler"></param> /// <param name="CtrlFormat">CtrlFormatString:控件名和字段名的对应关系,如"{0}1" ,在每个控件后加上"1"</param> /// <returns></returns> public static bool DisplayRowDataUponWebDoc(Control ctrl,DataRow MyRow,FormatDateTimeHandler DateTimeHandler,string CtrlFormat) { DataTable MyTable = MyRow.Table; //foreach( Control con in ctrl.Controls) for(int x=0;x<MyTable.Columns.Count;x++) { #region 获取Row值 和页面上的控件 Control con = ctrl.FindControl(string.Format(CtrlFormat, MyTable.Columns[x].ColumnName)); if(con == null) continue; //string CtrlName= con.ID; //if( (CtrlName == null) || (CtrlName == "")) continue; //if(!( MyTable.Columns.IndexOf(CtrlName) >=0 )) continue; Type CtrlType = con.GetType(); #endregion #region 根据类型加载数据到页面 if(CtrlType == typeof(Label)) { #region 标签 ((Label)con).Text = MyRow[x].ToString(); #endregion continue; } if(CtrlType == typeof(TextBox)) { #region 文本框 if(MyTable.Columns[x].DataType== typeof(DateTime)) //日期处理方法 { if(DateTimeHandler!= null) { if(MyRow[x] != DBNull.Value) ((TextBox)con).Text = DateTimeHandler((DateTime)MyRow[x],MyTable.Columns[x].ColumnName); } else { //默认精确到天 string s = MyRow[x].ToString(); int p = s.IndexOf(" "); ((TextBox)con).Text = p>=0 ?s.Substring(0,p):s; } } else ((TextBox)con).Text = MyRow[x].ToString(); #endregion continue; } if(CtrlType == typeof(DropDownList)) { #region 下拉框 DropDownList DL = (DropDownList)con; DL.SelectedIndex = -1; ListItem LI = DL.Items.FindByValue(MyRow[x].ToString()); if(LI!=null) DL.SelectedIndex = DL.Items.IndexOf(LI); else DL.SelectedIndex = DL.Items.IndexOf( DL.Items.FindByText(MyRow[x].ToString()) ); #endregion continue; } if(CtrlType == typeof(CheckBox)) { #region 单选框 if(MyRow[x] != DBNull.Value) ((CheckBox)con).Checked = Convert.ToBoolean( MyRow[x] ); #endregion continue; } if(CtrlType == typeof(Image)) { #region 图片域 ((System.Web.UI.WebControls.Image) con).ImageUrl = MyRow[x].ToString(); #endregion continue; } if(CtrlType == typeof(RadioButtonList)) { #region 多选一 RadioButtonList list = con as RadioButtonList; list.SelectedIndex = -1; string Value=MyRow[x].ToString(); ListItem item = list.Items.FindByValue(Value); if(item != null) { list.SelectedIndex = list.Items.IndexOf(item); } else { item = list.Items.FindByText(Value); if(item != null) list.SelectedIndex = list.Items.IndexOf(item); } #endregion continue; } if(CtrlType == typeof(CheckBoxList)) { #region 多选多 选项之间用","隔开 CheckBoxList list = con as CheckBoxList; string []Values = MyRow[x].ToString().Split(','); foreach(ListItem item in list.Items) item.Selected = false; foreach(ListItem item in list.Items) { foreach(string v in Values) { if(item.Value == v) { item.Selected = true; break; } } } #endregion continue; } #endregion } return true; } #endregion #region AssignedTextValue private static object AssignedTextValue(Type ObjType,object val) { switch(ObjType.Name) { case "DateTime": return (val==null)||(val==DBNull.Value)||(val.ToString().Length<=0)?DBNull.Value:(object)Convert.ToDateTime(val); case "String": return val; case "Double": case "Int16": case "Int32": case "Int64": case "Decimal": if( (val==null)||(Convert.ToString( val ) == "")) return 0; else return val; default: return val; } } #endregion #region ReadHttpPostDataToRow /// <summary> ///将ctrl的元素数据按照名称-字段匹配的方式读入返回值里 ///返回的 Hashtable Keys是找到了相关数据的MyTable的Columns[x]的集合 /// </summary> public static System.Collections.Hashtable ReadHttpPostDataToRow(Control ctrl,DataTable MyTable) { //DataTable MyTable= NewRow.Table; Hashtable Datas = new Hashtable(); //foreach( Control con in ctrl.Controls) for(int x=0;x<MyTable.Columns.Count;x++) { #region 获取页面上的控件 DataColumn Column = MyTable.Columns[x]; Control con = ctrl.FindControl(Column.ColumnName); if(con==null)continue;// string CtrlName= con.ID;// if( (CtrlName == null) || (CtrlName == "")) continue;// int ColIndex =MyTable.Columns.IndexOf(CtrlName);// if(!( ColIndex >=0 )) continue; Type CtrlType = con.GetType(); Type DataType = Column.DataType; #endregion #region 根据类型加载数据到页面 if(CtrlType == typeof(Label)) { #region 标签 #endregion continue; } if(CtrlType == typeof(TextBox)) { #region 文本框 Datas.Add( Column,AssignedTextValue( DataType ,((TextBox)con).Text)); #endregion continue; } if(CtrlType == typeof(DropDownList)) { #region 下拉框 if(((DropDownList)con).SelectedIndex>=0) Datas.Add( Column,((DropDownList)con).SelectedValue); else Datas.Add( Column,DBNull.Value); #endregion continue; } if(CtrlType == typeof(CheckBox)) { #region 单选框 Datas.Add(Column,((CheckBox)con).Checked); #endregion continue; } if(CtrlType == typeof(Image)) { #region 图片域 #endregion continue; } if(CtrlType == typeof(RadioButtonList)) { #region 多选一 if(((RadioButtonList)con).SelectedIndex>=0) Datas.Add(Column,((RadioButtonList)con).SelectedValue); else Datas.Add(Column,DBNull.Value); #endregion continue; } if(CtrlType == typeof(CheckBoxList)) { #region 多选多 选项之间用","隔开 CheckBoxList list = con as CheckBoxList; string s =""; foreach(ListItem item in list.Items) { if(item.Selected) { if(s.Length ==0) s = item.Value; else s+=","+item.Value; } } Datas.Add(Column,s); #endregion continue; } #endregion } return Datas; } /// <summary> ///将ctrl的元素数据按照名称-字段匹配的方式读入返回值里 ///返回的 Hashtable Keys是找到了相关数据的MyTable的Columns[x]的集合 /// </summary> /// <param name="ctrl"></param> /// <param name="MyTable"></param> /// <param name="CtrlFormat">CtrlFormatString:控件名和字段名的对应关系,如"{0}1" ,在每个控件后加上"1"</param> /// <returns></returns> public static System.Collections.Hashtable ReadHttpPostDataToRow(Control ctrl,DataTable MyTable ,string CtrlFormat) { //DataTable MyTable= NewRow.Table; Hashtable Datas = new Hashtable(); //foreach( Control con in ctrl.Controls) for(int x=0;x<MyTable.Columns.Count;x++) { #region 获取页面上的控件 DataColumn Column = MyTable.Columns[x]; Control con = ctrl.FindControl(string.Format(CtrlFormat, Column.ColumnName)); if(con==null)continue;// string CtrlName= con.ID;// if( (CtrlName == null) || (CtrlName == "")) continue;// int ColIndex =MyTable.Columns.IndexOf(CtrlName);// if(!( ColIndex >=0 )) continue; Type CtrlType = con.GetType(); Type DataType = Column.DataType; #endregion #region 根据类型加载数据到页面 if(CtrlType == typeof(Label)) { #region 标签 #endregion continue; } if(CtrlType == typeof(TextBox)) { #region 文本框 Datas.Add( Column,AssignedTextValue( DataType ,((TextBox)con).Text)); #endregion continue; } if(CtrlType == typeof(DropDownList)) { #region 下拉框 if(((DropDownList)con).SelectedIndex>=0) Datas.Add( Column,((DropDownList)con).SelectedValue); else Datas.Add( Column,DBNull.Value); #endregion continue; } if(CtrlType == typeof(CheckBox)) { #region 单选框 Datas.Add(Column,((CheckBox)con).Checked); #endregion continue; } if(CtrlType == typeof(Image)) { #region 图片域 #endregion continue; } if(CtrlType == typeof(RadioButtonList)) { #region 多选一 if(((RadioButtonList)con).SelectedIndex>=0) Datas.Add(Column,((RadioButtonList)con).SelectedValue); else Datas.Add(Column,DBNull.Value); #endregion continue; } if(CtrlType == typeof(CheckBoxList)) { #region 多选多 选项之间用","隔开 CheckBoxList list = con as CheckBoxList; string s =""; foreach(ListItem item in list.Items) { if(item.Selected) { if(s.Length ==0) s = item.Value; else s+=","+item.Value; } } Datas.Add(Column,s); #endregion continue; } #endregion } return Datas; } #endregion #region GetUpdateCommand /// <summary> /// 根据输入的数据 生成更新数据库的Command对象 :Update {0} set (statements in datas) where Conditions /// </summary> /// <param name="Datas">Hashtable对象应为ReadHttpPostDataToRow的返回值 </param> /// <param name="TableName">表名</param> /// <returns>返回可以直接执行的SqlCommand</returns> public static SqlCommand GetUpdateCommand(Hashtable Datas,string TableName,string Conditions) { SqlCommand cmd = new SqlCommand(); string s=""; foreach(DataColumn Col in Datas.Keys) { #region 添加参数 if(Col.DataType == typeof(int)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Int); } else if(Col.DataType == typeof(Decimal)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Decimal); } else if(Col.DataType == typeof(float)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Float); } else if(Col.DataType == typeof(DateTime)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.DateTime); } else if(Col.DataType == typeof(bool)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Bit); } else //if( Col.DataType == typeof(string)) //默认剩余的全部为字符型 { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.VarChar); } cmd.Parameters["@"+Col.ColumnName].Value = Datas[Col]; if(s.Length ==0) s =string.Format(" {0}=@{0} ",Col.ColumnName); else s =string.Format("{0} , {1}=@{1} ",s,Col.ColumnName); #endregion } cmd.CommandText =string.Format( "update {0} set {1} where {2}" ,TableName,s ,Conditions); return cmd; } #endregion #region GetInsertCommand /// <summary> /// 根据输入的数据 生成更新数据库的Command对象 :Insert into{0}({1}values{2} /// 从ReadHttpPostDataToRow读出的数据可能是不全的 比如缺少关联字段 或者 自定义的自增字段 需要在调用该函数之前生成这些数据 /// </summary> /// <param name="Datas">Hashtable对象应为ReadHttpPostDataToRow的返回值</param> /// <param name="TableName">表名</param> /// <returns>返回可以直接执行的SqlCommand</returns> public static SqlCommand GetInsertCommand(Hashtable Datas,string TableName) { SqlCommand cmd = new SqlCommand(); string s=""; string s1=""; foreach(DataColumn Col in Datas.Keys) { #region 添加参数 if(Col.DataType == typeof(int)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Int); } else if(Col.DataType == typeof(Decimal)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Decimal); } else if(Col.DataType == typeof(float)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Float); } else if(Col.DataType == typeof(DateTime)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.DateTime); } else if(Col.DataType == typeof(bool)) { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Bit); } else //if( Col.DataType == typeof(string)) //默认剩余的全部为字符型 { cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.VarChar); } cmd.Parameters["@"+Col.ColumnName].Value = Datas[Col]; if(s.Length ==0) { s =string.Format(" {0} ",Col.ColumnName); s1 =string.Format(" @{0} ",Col.ColumnName); } else { s =string.Format("{0} , {1}",s,Col.ColumnName); s1 =string.Format("{0} , @{1}",s1,Col.ColumnName); } #endregion } //s1.Replace("#","@"); cmd.CommandText =string.Format( "insert into {0}({1})values({2})" ,TableName,s,s1); return cmd; } #endregion 显示到页面:dt = helper.QueryDataTable("select * from ncj_public where id_q ="+DataID+" and TypeID = "+TypeID);if(dt.Rows.Count>0) UIAccesser.DisplayRowDataUponWebDoc(this,dt.Rows[0],new UIAccesser.FormatDateTimeHandler(FormatDateTime));读取页面上的数据写入数据库DataTable DataContainer = helper.GetDataTable("Corp_StaffInfo");HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,DataContainer);helper.ExecuteNonQuery( UIAccesser.GetInsertCommand(datas,"Corp_StaffInfo")); truelove12(醉倒在巷口): 我的意思就是对界面上不同的控件判断,得出它的值,保存到对应自身ID的字段名中。显示也是同理。比如:有表custom(cu_code,cu_name,cu_type,cu_tel),在界面中有三textbox一dropdownlist:<asp:TextBox ID="cu_code" runat="server" size=16/><asp:TextBox ID="cu_name" runat="server" size=16/><asp:DropDownList ID="cu_type" runat="server"> <asp:ListItem value="种类一">种类一</asp:ListItem> <asp:ListItem value="种类二">种类二</asp:ListItem> <asp:ListItem value="种类三">种类三</asp:ListItem></asp:DropDownList><asp:TextBox ID="cu_tel" runat="server" size=16/>,自动查找界面上的所有控件,判断控件的类型(多种类型,我这里只举例两种),取出它们页面上的值,保存到对应ID表示的字段名中去(ID所代表的字段名在指定的表中有,比如这个界面是客户资料的,我指明是表CUSTOM),我想这样的公用保存及显示程序应该是可以做的吧。 //查询语句获取表的字段信息DataTable dt = helper.QueryDataTable("select top 0 * from custom");//从页面上读取数据HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,DataContainer);//保存数据到数据库 //执行构造出来的 SQLCommandhelper.ExecuteNonQuery( UIAccesser.GetInsertCommand(datas,"custom")); 写错了://从页面上读取数据HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,dt); 显示一条信息到该页面:dt = helper.QueryDataTable("select top 1 * from custom);if(dt.Rows.Count>0) UIAccesser.DisplayRowDataUponWebDoc(this,dt.Rows[0],null); 麻烦,直接用asp.net2005,灵活性更强。 高手,我把crossrowman(godi) 兄台的代码作为了一个default1.cs文件,可是我不知道该怎样在我的product.aspx页面文件中调用显示及保存的方法?可不可以给我个实例。 有没有上述crossrowman兄台发的代码(c#)这样功能的VB版本?? private void insert(){ //构造sql语句 string InsertSql = "Insert into {0}({1}) values({2})"; StringBuilder insertValues = new StringBuilder(); StringBuilder cloumn_list = new StringBuilder(); string TableName="tablename"; SqlCommand sqlcom=new SqlCommand(); //循环取得页面控件,并构造sql语句 foreach(System.Web.UI.Control control in Page.Controls) { System.Data.IDataParameter iparam=new SqlParameter(); iparam.ParameterName = "@"+ control.ClientID; iparam.DbType = DbType.String; iparam.Value = GetControlValue(control);//传入控件,取得控件值 sqlcom.Parameters .Add(iparam); cloumn_list.Append(control.ClientID); insertValues.Append("@"+control.ClientID); cloumn_list.Append(","); insertValues.Append(","); } string cols=cloumn_list.ToString(); cols=cols.Substring(0,cols.Length -1); string values=insertValues.ToString(); values=values.Substring(0,values.Length -1); string sql = string.Format(InsertSql, TableName,cols ,values); sqlcom.CommandText =sql; ExecCommand(sqlcom);//调用执行sql的方法}public static int ExecCommand(SqlCommand sqlcom){ string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]; SqlConnection conn=new SqlConnection(ConnectionString); sqlcom.Connection =conn; conn.Open(); try { int rtn=sqlcom.ExecuteNonQuery(); return rtn; } catch(Exception ex) { throw ex; } finally { conn.Close(); } return 0;}//传入控件,取得控件值private string GetControlValue(System.Web.UI.Control control){ if( control == null ) return ""; string sValue = ""; if( control is TextBox ) { sValue = ((TextBox)control).Text.Trim(); } else if(control is Label) { sValue = ((Label)control).Text.Trim(); } else if(control is DropDownList) { sValue = ((ListControl)control).SelectedValue; } else if(control is CheckBox) { sValue = ((CheckBox)control).Checked.ToString(); } return sValue;}//以上是c#的根据页面控件来存入数据库的部分方法,可以进一步完善,从数据库取出显示到页面上就简单多了,直接赋值就可以了,没有在写。vb的语法不怎么的,所以你理解了怎么做后自己写vb的吧,^_^只是大概思路,没有测试,需修改。 using System.Data.SqlClient;using System.Text; 请问,提交数据 工作了,向同行朋友请教问题(sql,asp.net,ActiveX) javascript问题 求异步socket通信解决方法! 创CSDN项目团队 问个弱弱的问题,ASP.NET2005为什么在工程下不能添加项目?? 请问生成html页面后,点击量用哪种方法效率最好?UP者有分 分成二层asp:TextBox怎么样写?谢谢 关于日期查询的SQL 语句 error -- '類別未登錄 '? 有谁知道 serv-U 密码是怎么生成的。。。。(高难度加密) 求高手帮忙看下这样的效果如何做到???
另外,textbox和dropdownlist的表现方式本来就不一样.根本无法有公用的程序.
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
namespace TimeSpaceInfo.UI
{
/// <summary>
/// 读取或获取WebForm上的数据
/// </summary>
public class UIAccesser
{
public delegate string FormatDateTimeHandler(DateTime Time,string FieldName); public UIAccesser()
{
}
#region DisplayRowDataUponWebDoc
/// <summary>
///将MyRow的数据按照名称匹配的方式写入ctrl的元素里
/// </summary>
public static bool DisplayRowDataUponWebDoc(Control ctrl,DataRow MyRow,FormatDateTimeHandler DateTimeHandler)
{
DataTable MyTable = MyRow.Table; //foreach( Control con in ctrl.Controls)
for(int x=0;x<MyTable.Columns.Count;x++)
{
#region 获取Row值 和页面上的控件
Control con = ctrl.FindControl(MyTable.Columns[x].ColumnName);
if(con == null) continue;
string CtrlName= con.ID;
if( (CtrlName == null) || (CtrlName == "")) continue;
//if(!( MyTable.Columns.IndexOf(CtrlName) >=0 )) continue; Type CtrlType = con.GetType();
#endregion #region 根据类型加载数据到页面
if(CtrlType == typeof(Label))
{
#region 标签
((Label)con).Text = MyRow[CtrlName].ToString();
#endregion
continue;
}
if(CtrlType == typeof(TextBox))
{
#region 文本框
if(MyTable.Columns[x].DataType== typeof(DateTime)) //日期处理方法
{
if(DateTimeHandler!= null)
{
if(MyRow[CtrlName] != DBNull.Value)
((TextBox)con).Text = DateTimeHandler((DateTime)MyRow[CtrlName],CtrlName);
}
else
{
//默认精确到天
string s = MyRow[CtrlName].ToString();
int p = s.IndexOf(" ");
((TextBox)con).Text = p>=0 ?s.Substring(0,p):s;
}
}
else
((TextBox)con).Text = MyRow[CtrlName].ToString();
#endregion
continue;
}
if(CtrlType == typeof(DropDownList))
{
#region 下拉框
DropDownList DL = (DropDownList)con;
DL.SelectedIndex = -1;
ListItem LI = DL.Items.FindByValue(MyRow[CtrlName].ToString());
if(LI!=null)
DL.SelectedIndex = DL.Items.IndexOf(LI);
else
DL.SelectedIndex = DL.Items.IndexOf(
DL.Items.FindByText(MyRow[CtrlName].ToString()) );
#endregion
continue;
}
if(CtrlType == typeof(CheckBox))
{
#region 单选框
if(MyRow[CtrlName] != DBNull.Value)
((CheckBox)con).Checked = Convert.ToBoolean( MyRow[CtrlName] );
#endregion
continue;
}
if(CtrlType == typeof(Image))
{
#region 图片域
((System.Web.UI.WebControls.Image) con).ImageUrl = MyRow[CtrlName].ToString();
#endregion
continue;
}
if(CtrlType == typeof(RadioButtonList))
{
#region 多选一
RadioButtonList list = con as RadioButtonList;
list.SelectedIndex = -1;
string Value=MyRow[CtrlName].ToString();
ListItem item = list.Items.FindByValue(Value);
if(item != null)
{
list.SelectedIndex = list.Items.IndexOf(item);
}
else
{
item = list.Items.FindByText(Value);
if(item != null)
list.SelectedIndex = list.Items.IndexOf(item);
}
#endregion
continue;
}
if(CtrlType == typeof(CheckBoxList))
{
#region 多选多 选项之间用","隔开
CheckBoxList list = con as CheckBoxList;
string []Values = MyRow[CtrlName].ToString().Split(','); foreach(ListItem item in list.Items)
item.Selected = false;
foreach(ListItem item in list.Items)
{
foreach(string v in Values)
{
if(item.Value == v)
{
item.Selected = true;
break;
}
}
}
#endregion
continue;
}
#endregion
}
return true;
}
/// <summary>
/// 将MyRow的数据按照名称匹配的方式写入CtrlFormatString的元素里
/// </summary>
/// <param name="ctrl"></param>
/// <param name="MyRow"></param>
/// <param name="DateTimeHandler"></param>
/// <param name="CtrlFormat">CtrlFormatString:控件名和字段名的对应关系,如"{0}1" ,在每个控件后加上"1"</param>
/// <returns></returns>
public static bool DisplayRowDataUponWebDoc(Control ctrl,DataRow MyRow,FormatDateTimeHandler DateTimeHandler,string CtrlFormat)
{
DataTable MyTable = MyRow.Table; //foreach( Control con in ctrl.Controls)
for(int x=0;x<MyTable.Columns.Count;x++)
{
#region 获取Row值 和页面上的控件
Control con = ctrl.FindControl(string.Format(CtrlFormat, MyTable.Columns[x].ColumnName));
if(con == null) continue;
//string CtrlName= con.ID;
//if( (CtrlName == null) || (CtrlName == "")) continue;
//if(!( MyTable.Columns.IndexOf(CtrlName) >=0 )) continue; Type CtrlType = con.GetType();
#endregion #region 根据类型加载数据到页面
if(CtrlType == typeof(Label))
{
#region 标签
((Label)con).Text = MyRow[x].ToString();
#endregion
continue;
}
if(CtrlType == typeof(TextBox))
{
#region 文本框
if(MyTable.Columns[x].DataType== typeof(DateTime)) //日期处理方法
{
if(DateTimeHandler!= null)
{
if(MyRow[x] != DBNull.Value)
((TextBox)con).Text = DateTimeHandler((DateTime)MyRow[x],MyTable.Columns[x].ColumnName);
}
else
{
//默认精确到天
string s = MyRow[x].ToString();
int p = s.IndexOf(" ");
((TextBox)con).Text = p>=0 ?s.Substring(0,p):s;
}
}
else
((TextBox)con).Text = MyRow[x].ToString();
#endregion
continue;
}
if(CtrlType == typeof(DropDownList))
{
#region 下拉框
DropDownList DL = (DropDownList)con;
DL.SelectedIndex = -1;
ListItem LI = DL.Items.FindByValue(MyRow[x].ToString());
if(LI!=null)
DL.SelectedIndex = DL.Items.IndexOf(LI);
else
DL.SelectedIndex = DL.Items.IndexOf(
DL.Items.FindByText(MyRow[x].ToString()) );
#endregion
continue;
}
if(CtrlType == typeof(CheckBox))
{
#region 单选框
if(MyRow[x] != DBNull.Value)
((CheckBox)con).Checked = Convert.ToBoolean( MyRow[x] );
#endregion
continue;
}
if(CtrlType == typeof(Image))
{
#region 图片域
((System.Web.UI.WebControls.Image) con).ImageUrl = MyRow[x].ToString();
#endregion
continue;
}
if(CtrlType == typeof(RadioButtonList))
{
#region 多选一
RadioButtonList list = con as RadioButtonList;
list.SelectedIndex = -1;
string Value=MyRow[x].ToString();
ListItem item = list.Items.FindByValue(Value);
if(item != null)
{
list.SelectedIndex = list.Items.IndexOf(item);
}
else
{
item = list.Items.FindByText(Value);
if(item != null)
list.SelectedIndex = list.Items.IndexOf(item);
}
#endregion
continue;
}
if(CtrlType == typeof(CheckBoxList))
{
#region 多选多 选项之间用","隔开
CheckBoxList list = con as CheckBoxList;
string []Values = MyRow[x].ToString().Split(','); foreach(ListItem item in list.Items)
item.Selected = false;
foreach(ListItem item in list.Items)
{
foreach(string v in Values)
{
if(item.Value == v)
{
item.Selected = true;
break;
}
}
}
#endregion
continue;
}
#endregion
}
return true;
}
#endregion
private static object AssignedTextValue(Type ObjType,object val)
{
switch(ObjType.Name)
{
case "DateTime":
return (val==null)||(val==DBNull.Value)||(val.ToString().Length<=0)?DBNull.Value:(object)Convert.ToDateTime(val);
case "String":
return val;
case "Double":
case "Int16":
case "Int32":
case "Int64":
case "Decimal":
if( (val==null)||(Convert.ToString( val ) == ""))
return 0;
else
return val;
default:
return val;
}
}
#endregion #region ReadHttpPostDataToRow
/// <summary>
///将ctrl的元素数据按照名称-字段匹配的方式读入返回值里
///返回的 Hashtable Keys是找到了相关数据的MyTable的Columns[x]的集合
/// </summary>
public static System.Collections.Hashtable ReadHttpPostDataToRow(Control ctrl,DataTable MyTable)
{
//DataTable MyTable= NewRow.Table;
Hashtable Datas = new Hashtable();
//foreach( Control con in ctrl.Controls)
for(int x=0;x<MyTable.Columns.Count;x++)
{
#region 获取页面上的控件
DataColumn Column = MyTable.Columns[x];
Control con = ctrl.FindControl(Column.ColumnName);
if(con==null)continue;
// string CtrlName= con.ID;
// if( (CtrlName == null) || (CtrlName == "")) continue;
// int ColIndex =MyTable.Columns.IndexOf(CtrlName);
// if(!( ColIndex >=0 )) continue; Type CtrlType = con.GetType();
Type DataType = Column.DataType; #endregion #region 根据类型加载数据到页面
if(CtrlType == typeof(Label))
{
#region 标签
#endregion
continue;
}
if(CtrlType == typeof(TextBox))
{
#region 文本框
Datas.Add( Column,AssignedTextValue( DataType ,((TextBox)con).Text));
#endregion
continue;
}
if(CtrlType == typeof(DropDownList))
{
#region 下拉框
if(((DropDownList)con).SelectedIndex>=0)
Datas.Add( Column,((DropDownList)con).SelectedValue);
else
Datas.Add( Column,DBNull.Value);
#endregion
continue;
}
if(CtrlType == typeof(CheckBox))
{
#region 单选框
Datas.Add(Column,((CheckBox)con).Checked);
#endregion
continue;
}
if(CtrlType == typeof(Image))
{
#region 图片域
#endregion
continue;
}
if(CtrlType == typeof(RadioButtonList))
{
#region 多选一
if(((RadioButtonList)con).SelectedIndex>=0)
Datas.Add(Column,((RadioButtonList)con).SelectedValue);
else
Datas.Add(Column,DBNull.Value);
#endregion
continue;
}
if(CtrlType == typeof(CheckBoxList))
{
#region 多选多 选项之间用","隔开
CheckBoxList list = con as CheckBoxList;
string s ="";
foreach(ListItem item in list.Items)
{
if(item.Selected)
{
if(s.Length ==0)
s = item.Value;
else
s+=","+item.Value;
}
}
Datas.Add(Column,s);
#endregion
continue;
}
#endregion
}
return Datas;
}
/// <summary>
///将ctrl的元素数据按照名称-字段匹配的方式读入返回值里
///返回的 Hashtable Keys是找到了相关数据的MyTable的Columns[x]的集合
/// </summary>
/// <param name="ctrl"></param>
/// <param name="MyTable"></param>
/// <param name="CtrlFormat">CtrlFormatString:控件名和字段名的对应关系,如"{0}1" ,在每个控件后加上"1"</param>
/// <returns></returns>
public static System.Collections.Hashtable ReadHttpPostDataToRow(Control ctrl,DataTable MyTable ,string CtrlFormat)
{
//DataTable MyTable= NewRow.Table;
Hashtable Datas = new Hashtable();
//foreach( Control con in ctrl.Controls)
for(int x=0;x<MyTable.Columns.Count;x++)
{
#region 获取页面上的控件
DataColumn Column = MyTable.Columns[x];
Control con = ctrl.FindControl(string.Format(CtrlFormat, Column.ColumnName));
if(con==null)continue;
// string CtrlName= con.ID;
// if( (CtrlName == null) || (CtrlName == "")) continue;
// int ColIndex =MyTable.Columns.IndexOf(CtrlName);
// if(!( ColIndex >=0 )) continue; Type CtrlType = con.GetType();
Type DataType = Column.DataType; #endregion #region 根据类型加载数据到页面
if(CtrlType == typeof(Label))
{
#region 标签
#endregion
continue;
}
if(CtrlType == typeof(TextBox))
{
#region 文本框
Datas.Add( Column,AssignedTextValue( DataType ,((TextBox)con).Text));
#endregion
continue;
}
if(CtrlType == typeof(DropDownList))
{
#region 下拉框
if(((DropDownList)con).SelectedIndex>=0)
Datas.Add( Column,((DropDownList)con).SelectedValue);
else
Datas.Add( Column,DBNull.Value);
#endregion
continue;
}
if(CtrlType == typeof(CheckBox))
{
#region 单选框
Datas.Add(Column,((CheckBox)con).Checked);
#endregion
continue;
}
if(CtrlType == typeof(Image))
{
#region 图片域
#endregion
continue;
}
if(CtrlType == typeof(RadioButtonList))
{
#region 多选一
if(((RadioButtonList)con).SelectedIndex>=0)
Datas.Add(Column,((RadioButtonList)con).SelectedValue);
else
Datas.Add(Column,DBNull.Value);
#endregion
continue;
}
if(CtrlType == typeof(CheckBoxList))
{
#region 多选多 选项之间用","隔开
CheckBoxList list = con as CheckBoxList;
string s ="";
foreach(ListItem item in list.Items)
{
if(item.Selected)
{
if(s.Length ==0)
s = item.Value;
else
s+=","+item.Value;
}
}
Datas.Add(Column,s);
#endregion
continue;
}
#endregion
}
return Datas;
}
#endregion
/// <summary>
/// 根据输入的数据 生成更新数据库的Command对象 :Update {0} set (statements in datas) where Conditions
/// </summary>
/// <param name="Datas">Hashtable对象应为ReadHttpPostDataToRow的返回值 </param>
/// <param name="TableName">表名</param>
/// <returns>返回可以直接执行的SqlCommand</returns>
public static SqlCommand GetUpdateCommand(Hashtable Datas,string TableName,string Conditions)
{
SqlCommand cmd = new SqlCommand();
string s="";
foreach(DataColumn Col in Datas.Keys)
{
#region 添加参数
if(Col.DataType == typeof(int))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Int);
}
else if(Col.DataType == typeof(Decimal))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Decimal);
}
else if(Col.DataType == typeof(float))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Float);
}
else if(Col.DataType == typeof(DateTime))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.DateTime);
}
else if(Col.DataType == typeof(bool))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Bit);
} else //if( Col.DataType == typeof(string)) //默认剩余的全部为字符型
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.VarChar);
}
cmd.Parameters["@"+Col.ColumnName].Value = Datas[Col];
if(s.Length ==0)
s =string.Format(" {0}=@{0} ",Col.ColumnName);
else
s =string.Format("{0} , {1}=@{1} ",s,Col.ColumnName);
#endregion
}
cmd.CommandText =string.Format( "update {0} set {1} where {2}" ,TableName,s ,Conditions);
return cmd;
}
#endregion #region GetInsertCommand
/// <summary>
/// 根据输入的数据 生成更新数据库的Command对象 :Insert into{0}({1}values{2}
/// 从ReadHttpPostDataToRow读出的数据可能是不全的 比如缺少关联字段 或者 自定义的自增字段 需要在调用该函数之前生成这些数据
/// </summary>
/// <param name="Datas">Hashtable对象应为ReadHttpPostDataToRow的返回值</param>
/// <param name="TableName">表名</param>
/// <returns>返回可以直接执行的SqlCommand</returns>
public static SqlCommand GetInsertCommand(Hashtable Datas,string TableName)
{
SqlCommand cmd = new SqlCommand();
string s="";
string s1="";
foreach(DataColumn Col in Datas.Keys)
{
#region 添加参数
if(Col.DataType == typeof(int))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Int);
}
else if(Col.DataType == typeof(Decimal))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Decimal);
}
else if(Col.DataType == typeof(float))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Float);
}
else if(Col.DataType == typeof(DateTime))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.DateTime);
}
else if(Col.DataType == typeof(bool))
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.Bit);
} else //if( Col.DataType == typeof(string)) //默认剩余的全部为字符型
{
cmd.Parameters.Add("@"+Col.ColumnName,SqlDbType.VarChar);
}
cmd.Parameters["@"+Col.ColumnName].Value = Datas[Col];
if(s.Length ==0)
{
s =string.Format(" {0} ",Col.ColumnName);
s1 =string.Format(" @{0} ",Col.ColumnName);
}
else
{
s =string.Format("{0} , {1}",s,Col.ColumnName);
s1 =string.Format("{0} , @{1}",s1,Col.ColumnName);
}
#endregion
}
//s1.Replace("#","@");
cmd.CommandText =string.Format( "insert into {0}({1})values({2})" ,TableName,s,s1);
return cmd;
}
#endregion
dt = helper.QueryDataTable("select * from ncj_public where id_q ="+DataID+" and TypeID = "+TypeID);
if(dt.Rows.Count>0)
UIAccesser.DisplayRowDataUponWebDoc(this,dt.Rows[0],new UIAccesser.FormatDateTimeHandler(FormatDateTime));读取页面上的数据写入数据库
DataTable DataContainer = helper.GetDataTable("Corp_StaffInfo");
HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,DataContainer);
helper.ExecuteNonQuery( UIAccesser.GetInsertCommand(datas,"Corp_StaffInfo"));
我的意思就是对界面上不同的控件判断,得出它的值,保存到对应自身ID的字段名中。显示也是同理。比如:有表custom(cu_code,cu_name,cu_type,cu_tel),在界面中有三textbox一dropdownlist:
<asp:TextBox ID="cu_code" runat="server" size=16/>
<asp:TextBox ID="cu_name" runat="server" size=16/>
<asp:DropDownList ID="cu_type" runat="server">
<asp:ListItem value="种类一">种类一</asp:ListItem>
<asp:ListItem value="种类二">种类二</asp:ListItem>
<asp:ListItem value="种类三">种类三</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="cu_tel" runat="server" size=16/>
,自动查找界面上的所有控件,判断控件的类型(多种类型,我这里只举例两种),取出它们页面上的值,保存到对应ID表示的字段名中去(ID所代表的字段名在指定的表中有,比如这个界面是客户资料的,我指明是表CUSTOM),我想这样的公用保存及显示程序应该是可以做的吧。
DataTable dt = helper.QueryDataTable("select top 0 * from custom");
//从页面上读取数据
HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,DataContainer);
//保存数据到数据库
//执行构造出来的 SQLCommand
helper.ExecuteNonQuery( UIAccesser.GetInsertCommand(datas,"custom"));
//从页面上读取数据
HastTable datas = UIAccesser.ReadHttpPostDataToRow(this,dt);
dt = helper.QueryDataTable("select top 1 * from custom);
if(dt.Rows.Count>0)
UIAccesser.DisplayRowDataUponWebDoc(this,dt.Rows[0],null);
{
//构造sql语句
string InsertSql = "Insert into {0}({1}) values({2})";
StringBuilder insertValues = new StringBuilder();
StringBuilder cloumn_list = new StringBuilder();
string TableName="tablename";
SqlCommand sqlcom=new SqlCommand();
//循环取得页面控件,并构造sql语句
foreach(System.Web.UI.Control control in Page.Controls)
{
System.Data.IDataParameter iparam=new SqlParameter();
iparam.ParameterName = "@"+ control.ClientID;
iparam.DbType = DbType.String;
iparam.Value = GetControlValue(control);//传入控件,取得控件值
sqlcom.Parameters .Add(iparam); cloumn_list.Append(control.ClientID);
insertValues.Append("@"+control.ClientID); cloumn_list.Append(",");
insertValues.Append(",");
}
string cols=cloumn_list.ToString();
cols=cols.Substring(0,cols.Length -1); string values=insertValues.ToString();
values=values.Substring(0,values.Length -1);
string sql = string.Format(InsertSql, TableName,cols ,values);
sqlcom.CommandText =sql;
ExecCommand(sqlcom);//调用执行sql的方法
}public static int ExecCommand(SqlCommand sqlcom)
{
string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn=new SqlConnection(ConnectionString);
sqlcom.Connection =conn;
conn.Open();
try
{
int rtn=sqlcom.ExecuteNonQuery();
return rtn;
}
catch(Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
return 0;
}
//传入控件,取得控件值
private string GetControlValue(System.Web.UI.Control control)
{
if( control == null ) return "";
string sValue = "";
if( control is TextBox )
{
sValue = ((TextBox)control).Text.Trim();
}
else if(control is Label)
{
sValue = ((Label)control).Text.Trim();
}
else if(control is DropDownList)
{
sValue = ((ListControl)control).SelectedValue;
}
else if(control is CheckBox)
{
sValue = ((CheckBox)control).Checked.ToString();
}
return sValue;
}//以上是c#的根据页面控件来存入数据库的部分方法,可以进一步完善,从数据库取出显示到页面上就简单多了,直接赋值就可以了,没有在写。vb的语法不怎么的,所以你理解了怎么做后自己写vb的吧,^_^
只是大概思路,没有测试,需修改。
using System.Text;