首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

DataViewRow.Cells[]取不出数据的有关问题

2012-01-11 
DataViewRow.Cells[]取不出数据的问题?foreach(GridViewRow gr in GridView1.Rows){CheckBox chb (Check

DataViewRow.Cells[]取不出数据的问题?
foreach(GridViewRow gr in GridView1.Rows)
  {
  CheckBox chb = (CheckBox)gr.FindControl("chb_check");
  if (chb.Checked)
  {
  string stuID = gr.Cells[2].Text.ToString();
  string stuName = gr.Cells[3].Text.ToString();
  }
  }
我调试的时候stuID,stuName都为空,请问cells[n].Text取的是项中那个数据呢,ItemTemplate,EditItemTemplate??我已经把该列转为模板列了.ItemTemplate,EditItemTemplate里都有控件?我就是想取控件中的值,不想再用findcontrol这个方法

[解决办法]
这样取没有问题

CheckBox能找到吗?
[解决办法]
拖个Gridview进来,把下列代码放到FormLoad事件中

C# code
    DataSet ds = new DataSet();     ds.Tables.Add("namelist");     ds.Tables(0).Columns.Add("ID", typeof(Int32));     ds.Tables(0).Columns.Add("Name", typeof(string));     ds.Tables(0).Columns.Add("c", typeof(bool));     ds.Tables(0).Rows.Add(new object[] { 1, "Li", 0 });     ds.Tables(0).Rows.Add(new object[] { 2, "Lu", 1 });         GridView1.DataSource = ds;     GridView1.DataBind();         foreach (GridViewRow gr in GridView1.Rows) {         CheckBox ckb = (CheckBox)gr.Cells(2).Controls(0);         if (ckb.Checked) {             string strName = gr.Cells(1).Text.ToString;             Response.Write(strName);         }     }
[解决办法]
非常正确呀。

[解决办法]
如果已经是模板列,用Cells[index].Text是得不到里面的内容的,必须使用FindControl方法,其实理由很简单,TemplateField里面可以有多个控件,比如文本框,标签等等,你取里面的Cells[index].Text,取的算是什么呢?

C# code
CheckBox chb;string stuID = string.Empty;string stuName = string.Empty;foreach (GridViewRow gr in GridView1.Rows){    chb = gr.FindControl("chb_check") as CheckBox;    if (chb != null && chb.Checked)    {        stuID = (gr.FindControl("id文本框的id") as TextBox).Text;        stuName = (gr.FindControl("name文本框的id") as TextBox).Text;    }}
[解决办法]
foreach(GridViewRow gr in GridView1.Rows) 

CheckBox chb = (CheckBox)gr.FindControl("chb_check"); 
if (chb.Checked) 

string stuID = chb.Text.ToString(); 
string stuName = chb.Text.ToString(); 


这样试一试 。。。

热点排行