求教关于多个Label如何用少量代码和数据库绑定?首先我做了一个表格,里面大约有10个Label,功能是调出每个部门的数量第一个Label我现在是这样写的测试通过
protected void lb1_Init(object sender, EventArgs e)
{
string sqlsum = "select count(number) as total from equipment where locus='检修西部'";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
SqlCommand thisCommand = new SqlCommand(sqlsum,conn);
thisCommand.CommandType = CommandType.Text;
try
{
thisCommand.Connection.Open();
SqlDataReader dr = thisCommand.ExecuteReader();
while (dr.Read())
{
this.lb1.Text = dr["total"].ToString();
}
}还有9个Label,但每个都这样写一堆一定很难看,而且又麻烦想知道有什么更快的方法可以一次搞定9个Label?谢谢啦
protected void lb1_Init(object sender, EventArgs e)
{
string sqlsum = "select count(number) as total from equipment where locus='检修西部'";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
SqlCommand thisCommand = new SqlCommand(sqlsum,conn);
thisCommand.CommandType = CommandType.Text;
try
{
thisCommand.Connection.Open();
SqlDataReader dr = thisCommand.ExecuteReader();
while (dr.Read())
{
this.lb1.Text = dr["total"].ToString();
}
}还有9个Label,但每个都这样写一堆一定很难看,而且又麻烦想知道有什么更快的方法可以一次搞定9个Label?谢谢啦
解决方案 »
- Web控件里的ViewState问题
- 难道有浏览器不支持style?简单
- 紧急向朋友求教,如何在后台.cs中生成DataGrid或者Datalist,感谢啊.
- vs2005上有象duwamish的例子吗?;;;;;;;;;;;;;;;;;;;
- 关于软件测试的问题! 是流程问题 非技术问题! 大家给点意见!!谢谢~高手!大侠!强人!
- 求用MD5加密解密的源码
- 我要在一个没有继承至page类的类中怎样才能使用Application呢?
- 如果你认为比我学得好那你就进来 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
- 初用datagrid碰到的问题,请不吝指教!谢谢!
- ASP.NET中怎么调用公共模块或公共函数
- 我用ajax返回一个Datatable,请问如何在前台如何获取table的内容
- 请教一SQL语句,回复就有分,在线等
然后
for(int i=0;i<10:i++)
{
}
循环一下就能将资料分别赋给10个label了这样只要读一次数据库,而不需要读10次了。
一楼的for(int i=0;i <10:i++) 怎么写啊能给写具体代码吗?
顺便提醒下楼主, 用数据控件岂不是更简单?一个label放在模板列,哪怕有100,1000个,同样给你显示出来你这样做太麻烦呵呵
{
//按部门id排序统计各个部门数量
string sqlsum = "select count(number)as total,deptid from equipment order by deptid;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
SqlCommand thisCommand = new SqlCommand(sqlsum,conn);
thisCommand.CommandType = CommandType.Text;
try
{
thisCommand.Connection.Open();
SqlDataReader dr = thisCommand.ExecuteReader();
int i=1;
//按顺序绑定
while (dr.Read())
{
Lable lb=(Label)Page.FindControl("lb"+i.ToString());
lb.Text = dr["total"].ToString();
}
}
我不清楚你的10个字段分别是什么啊。
我自己打个比方,第一个lable放数量,第二个lable放甲部门,第三个lable放乙部门老大名字
……
你在SQL中用union把所有的东西放到一个table中去,表的结构如下:txt
----------
35
IT部門
孔乙己
……然后在C#中你将它们一条条的串成一个string,如“35,IT部门,孔乙己……”//代码只是一个思路
DataTable txtRead = DBHelp.ExecuteReader(strSQL);
string txt= "";
if (txt!= null && txtRead.Rows.Count > 0)
{
foreach (DataRow dr in txtRead.Rows)
{
txt+= dr[0].ToString().Trim();
txt+= ",";
}
}
if (!string.IsNullOrEmpty(txt))
{
txt= txt.TrimEnd(',');
}
return txt;最后你用C#的split切割字符串,再将数组中的赋给lable.string[] Field = txt.Split(',');
lbSubject.Text = Field[0];
lbClass.Text = Field[1];
lbContent.Text = Field[2];
……