XuGang

记录一个程序员的成长

 

关于DataGrid数据绑定后对字段进行替换的问题与办法

在项目中,我再次用到了VS2003的DataGrid控件进行数据显示。
根据要求,我需要在第8列将MSSQL2000中的varchar类型的数据"0"与"1"显示成"未传送"与"已传送"
于是我便在DataGrid与DataSet进行DataBind()后,再用for循环进行替换:

myDataGrid.DataSource=myDataSet;
myDataGrid.DataBind();
for(int i=0;i<myDataSet.Tables[0].Rows.Count;i++)
{
   
if(myDataGrid.Items[i].Cells[7].Text=="0")
   {
      myDataGrid.Items[i].Cells[
7].Text="未传送";
   }
   
else
   {
      myDataGrid.Items[i].Cells[
7].Text="已传送";
   }
}


运行没有问题,于是我接着做DataGrid的分页功能,将页面设置成20行,并添加事件:

myDataGrid.CurrentPageIndex = e.NewPageIndex;
         
myDataGrid.DataSource
=myDataSet;
myDataGrid.DataBind();


再一运行,报错了。显示大概是前面用for循环进行替换超出index范围值。
怎么办?我立刻想到了两种办法:
1.直接把数据库中的varchar类型的数据"0"与"1"更改成"未传送"与"已传送"
2.用模板列与DataBinder.Eval进行更改绑定(我选择此方法)
.aspx

<asp:TemplateColumn HeaderText="传递状态">
   
<ItemTemplate>
      
<asp:Label id="sendLabel" runat="server" Text='<%#str_Mark(DataBinder.Eval(Container,"DataItem.mark").ToString())%>'>
      
</asp:Label>
   
</ItemTemplate>
</asp:TemplateColumn>

.aspx.cs

//修改DataGrid 的 Mark 字段的显示
public string str_Mark(string strSign)
{
   
string strMassage = "";
   
if(strSign == "0")
   {
      strMassage 
= "<font color='red'>"+"未传送"+"</font>";                
   }
   
else if(strSign == "1")
   {
      strMassage 
= "<font color='green'>"+"已传送"+"</font>";            
   }
   
return strMassage;
}


以前看了一篇文章,说Bind要比Eval的功能和性能要好,大家也可以进行一些更改替换。
当然,如果大家有比我更好的解决办法,不吝赐教!

posted on 2007-11-29 10:34  钢钢  阅读(1267)  评论(6编辑  收藏  举报

导航