无法从Gridview获取值
本文关键字:获取 Gridview | 更新日期: 2023-09-27 17:50:35
你好,我有一个gridview命名为FolderGridView。在GridView中有一个模板字段,在模板字段中我指定了一个链接按钮。现在我无法从我的codeBehind中的linkButton获取值。
<asp:GridView ID="FolderGridView" runat="server"
AutoGenerateColumns = "False"
AllowPaging ="True" OnPageIndexChanging ="FolderGridView_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None"
>
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="FolderCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Folder Name">
<ItemTemplate>
<asp:LinkButton Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my code Behind
for (int i = 0; i < FolderGridView.Rows.Count; i++)
{
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string FileName = (string)FolderGridView.Rows[i].Cells[1].Text.ToString();
}
}
我已经调试了后面的代码部分。在FileName中,当我到达这一点时,我得到一个空字符串。如何从模板字段获取值呢?
单元格中的文本在LinkButton控件内部,所以首先你必须获得GridView行的LinkButton控件,然后你可以访问text属性。下面的代码应该在您的情况下工作:
for (int i = 0; i < FolderGridView.Rows.Count; i++){
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true){
foreach (Control ctl in FolderGridView.Rows(i).Cells(1).Controls) {
if (ctl is LinkButton) {
string filename = ((LinkButton)ctl).Text;
}
}
}
用
替换链接按钮编辑:LinkButton:
<asp:LinkButton ID="LinkButton1" AutoPostBack="True" OnClick="someMethod" Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
和
背后的代码protected void someMethod(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView5.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string probname = chk.Text;
}
}
}