日期:2014-05-17  浏览次数:20490 次

gridview如何获取模板列中的值
如题。我在模板列asp:TemplateField中加控件比如<asp:label>还有input hidden都不行,得到的都是空值,郁闷。换了个方法用asp:BoundField,如果设置visible=false,还是得不到
我用的gridview.Rows[i].Cells[3].Text
用<asp:label>时这样写的,((label)gridview.Rows[i].Cells[3].FindControl("lb")).Text,均不行。。。

------解决方案--------------------
可以考虑用JavaScript脚本,例如:
function Select()
{
//获取鼠标点击的元素
var e=event.srcElement;
//获取元素所在的行的行号(表头行号从0开始)。注意:parentElement只适用于IE浏览器,而parentNode则符合DOM标准。
//var rowIndex=e.parentElement.parentElement.rowIndex ;
var rowIndex=e.parentNode.rowIndex ;
//获取GridView控件
var gdview=document.getElementById("<%=dvList.ClientID %>");
//分别获取选定行标注点的X、Y坐标
// var value=gdview.rows(rowIndex).cells(2).innerText;

window.opener.document.getElementById("txtClientID").value=gdview.rows(rowIndex).cells(1).innerText;
window.opener.document.getElementById("txtClientName").value=gdview.rows(rowIndex).cells(2).innerText;
window.opener.document.getElementById("txtAddress").value=gdview.rows(rowIndex).cells(3).innerText;
window.opener.document.getElementById("txtOfficePhone").value=gdview.rows(rowIndex).cells(4).innerText;
window.opener.document.getElementById("txtLinkManCall").value=gdview.rows(rowIndex).cells(5).innerText;
window.opener.document.getElementById("txtMobile").value=gdview.rows(rowIndex).cells(6).innerText;
 
window.close();
//
window.close();
 
}

------解决方案--------------------
在GridView中加入如下代码,在双击某行的时候会获取某行的值
if (e.Row.RowIndex >= 0)
{
e.Row.Attributes.Add("onMouseOver", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#CCCCDD'");
e.Row.Attributes.Add("onMouseOut", "this.style.backgroundColor=currentcolor");
e.Row.Attributes.Add("ondblclick", "Select(this,'"+e.Row.Cells[0].Text.Trim()+"')");
//CrmUtility.SetDataViewCss(sender, e, strUrl);

}
------解决方案--------------------
直接((label)gridview.Rows[i].FindControl("lb")).Text试试。
------解决方案--------------------
放在模板列中的控件要用findControl方法找到后,才能取到值
比如label ID为Label1
C# code

Label lbl=(Label)GridView1.Rows[i].FindControl("Label1");  //其他控件方法也是这样

------解决方案--------------------
在不同行状态下获取单元格中的数据的方式
当绑定行处于正常状态时,数据位于单元格中,可以直接使用gv.Rows[e.RowIndex].Cells[0].Text获取
当绑定行处于编辑状态时,数据一般位于TextBox上,应使用((TextBox)gv.Rows[e.RowIndex].Cells[1].Controls[0]).Text来获取
当该列隐藏时,应当将该列转化为模板列后,使用((Label)gvBookCategory.Rows[i].Cells[0].Controls[1]).Text 来获取。
注:Controls中序号不是0,而是1.原因是当GridView运行的时候会在模板列中绑定显示数据的Label控件的前后分别加入一个Literal控件 

------解决方案--------------------
((label)gridview.Rows[i].Cells[3].FindControl("lb")).Text
改为
((Label)gridview.Rows[i].Cells[3].FindControl("lb")).Text