>我正在尝试使用 GridView 并从单击的行中取回数据。 我已经尝试了下面的代码,当我单击该行时,我会返回选定的索引,但是当我查看 GridView 中的实际行时,它们显示为空。 不知道我错过了什么。
.ASP制作我的网格。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"
CssClass="datatables" Width="100%"
DataSourceID="SqlDataSource1"
GridLines="None" ShowFooter="True" AllowSorting="True"
onrowcreated="GridView1_RowCreated"
onrowdatabound="GridView1_RowDataBound" ShowHeaderWhenEmpty="True"
onrowcommand="GridView1_RowCommand"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<HeaderStyle CssClass="hdrow" />
<RowStyle CssClass="datarow" />
<PagerStyle CssClass="cssPager" />
</asp:GridView>
在每行数据绑定上,我确保单击应设置所选索引。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
}
}
然后,当选定的索引通过单击此更改时,它会触发,我可以在第一行放置一个断点,我看到我单击的内容的索引存储在一个中。 但是,当我到达foreach时,它会跳过它,因为它显示GridView1的计数为0行。 理论上,它应该有几百行,当索引匹配时,它应该抓取第 6 个单元格中的数据并将其存储在字符串 b 中。 为什么我在点击时没有行?
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int a = GridView1.SelectedIndex
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex == a)
{
b = row.Cells[6].Text;
}
}
}
这是我的页面加载。
protected void Page_Load(object sender, EventArgs e)
{
c = HttpContext.Current.Session["c"].ToString();
SqlDataSource1.ConnectionString = //My secret
string strSelect = "SELECT columnnames from tablenames where c in (@c)
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectCommand = strSelect;
SqlDataSource1.SelectParameters.Add("c", c);
try
{
GridView1.DataBind();
}
catch (Exception e)
{
}
GridView1.AutoGenerateColumns = true;
}
尝试从 SelectedRow 属性中抓取该行:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string b = row.Cells[6].Text;
}
据我了解,当您使用这些数据源控件(如 SqlDataSource)时,不会在 PostBack 上重新填充行集合。
如果在尝试循环访问行之前在 GridView 上调用.DataBind()
,则可以使用现有代码:
GridView1.DataSourceID="SqlDataSource1";
GridView1.DataBind();
但这似乎有点笨拙。
看到您的Page_Load后,我看到您需要将数据绑定代码包装在if(!Page.IsPostBack)
块中。 每次回发时的数据绑定都会中断通过 ViewState ASP.NET 维护控件状态的过程。