DataSet绑定到页面的TextBox
#region 与页面控件绑定
/// <summary>
/// 与页面控件绑定
/// </summary>
/// <param name="ds">数据集</param>
protected void DB2Page(DataSet ds)
{
DB2Page(ds.Tables[0]);
}
protected void DB2Page(DataTable t, DataRow r)
{
//开始给文本框赋值
for (int i = 0; i < t.Columns.Count; i++)
{
SetControlValue(t.Columns[i].ColumnName, r[t.Columns[i].ColumnName]);
}
}
protected void DB2Page(SqlDataReader r)
{
for (int i = 0; i < r.FieldCount; i++)
{
SetControlValue(r.GetName(i), r[i]);
}
}
protected void DB2Page(DataTable t)
{
//开始给文本框赋值
if (t.Rows.Count < 1) return;
DataRow r = t.Rows[0];
DB2Page(t, r);
}
/// <summary>
/// 具体绑定控件
/// </summary>
/// <param name="ControlName">控件名</param>
/// <param name="Value">绑定的值</param>
private void SetControlValue(string ControlName, object Value)
{
Control c = FindControl(ControlName);
if (c == null) return;
if (c.GetType().Name == "TextBox")
{
System.Web.UI.WebControls.TextBox edt = (System.Web.UI.WebControls.TextBox)c;
if (c.ID.Substring(0, 4) == "fdbl")
{
edt.Text = TrimNum(Value.ToString());
}
else if (c.ID.Substring(0, 4) == "fmny")
{
if (Value.ToString() == "") edt.Text = "0.00";
else edt.Text = string.Format("{0:F2}", Convert.ToDouble(Value.ToString()));
}
else
{
edt.Text = Value.ToString();
}
}
if (c.GetType().Name == "DropDownList")
{
System.Web.UI.WebControls.DropDownList edt = (System.Web.UI.WebControls.DropDownList)c;
edt.SelectedValue = Value.ToString();
}
if (c.GetType().Name == "CheckBox")
{
System.Web.UI.WebControls.CheckBox edt = (System.Web.UI.WebControls.CheckBox)c;
edt.Checked = Convert.ToBoolean(Value.ToString());
}
if (c.GetType().Name == "GMDatePicker")
{
GrayMatterSoft.GMDatePicker edt = (GrayMatterSoft.GMDatePicker)c;
edt.DateString = Value.ToString();
}
}
/// <summary>
/// 去除小数点后多余的小数 0
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
private string TrimNum(string a)
{
if (a == "" || a == "0") return "0";
if (a.IndexOf(".", 0, a.Length) < 0) return a;
for (int i = a.Length; i >= 0; i--)
{
if (a.Substring(i - 1, 1) == "0")
a = a.Substring(0, i - 1);
else
break;
}
if (a.Substring(a.Length - 1, 1) == ".")
a = a.Substring(0, a.Length - 1);
return a;
}
#endregion
上面的代码,只是一个将DataSet自动绑定到textbox上去的一个简单的列子。