问题描述
我在表tb1中有个表,就像(表只有一个clounm)
ID
100
200
300
100
200
200
我用这个查询
从ID的tb1组中选择ID,count(ID)作为对,并具有MemberID HAVING Count(ID)> 0
我得到了结果
ID对
100 2
200 3
300 1
我在gridview中需要这样的结果
ID对
100 2
200 3
300 1
我在rowdatbound
中编写此代码
i have table in table tb1 like(table only one clounm)
ID
100
200
300
100
200
200
i used this query
select ID, count(ID) as pair From tb1 group by MemberID HAVING Count(ID)>0
i got result
id pair
100 2
200 3
300 1
i need result like this in gridview
ID pair
100 2
200 3
300 1
i write this code in rowdatbound
protected void gridtree_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblmessage = (Label)e.Row.FindControl("lblmessage");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
lblmessage.Text = dt.Rows[i]["pair"].ToString();
}
}
}
}
我得到这个结果
ID对
100 1
200 1
300 1
我需要结果
ID对
100 2
200 3
300 1
I am getting this result
ID pair
100 1
200 1
300 1
I need result
Id pair
100 2
200 3
300 1
推荐答案
for (int i = 0; i < dt.Rows.Count; i++)
{
lblmessage.Text = dt.Rows[i]["pair"].ToString();
}
每次触发gridtree_RowDataBound
事件时,都会在for循环中遍历DataTable dt
的所有行,并设置lblmessage.Text
,该值在每次迭代中都被覆盖.因此,从问题中给出的数据可以看出,DataTable dt的最后一行中的最后一个值1
,在上述事件之后将在lblmessage中可见.
但是我认为,为了在GridView
中显示数据,可以根据需要创建并填充具有Id, pair
列的DataTable
.然后,可以使用它以常规方式绑定到gridview.您可以考虑采用这种替代方法.
each time the gridtree_RowDataBound
event is fired, all rows of the DataTable dt
are traversed in the for loop and the lblmessage.Text
is set, which is being over written in each iteration. So the last value in the last row of the DataTable dt, which is 1
as seen from the data given in the question, will be visible in the lblmessage after the above event.
But I think, for the purpose of displaying the data in GridView
a DataTable
with columns Id, pair
can be created and populated as per requirement. Then it can be used to bind to the gridview in a normal way. You can consider this alternative.
<asp:GridView ID="gridtree1" runat="server" AutoGenerateColumns="false"
Width="100%" height="50%"
OnRowDataBound="gridtree_RowDataBound" style="margin-top: 3px" >
<Columns>
<asp:BoundField ReadOnly="true" HeaderText="ID" DataField="MemberID" SortExpression="MemberID" />
<asp:BoundField ReadOnly="true" HeaderText="pair" DataField="pair" SortExpression="pair" />
<%-- <asp:BoundField ReadOnly="true" HeaderText="award" DataField="pair" SortExpression="pair" />--%>
<asp:TemplateField HeaderText="Award" SortExpression="Pair">
<ItemTemplate>
<asp:Label ID="lblmessage" runat="server"> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
这篇关于gridview标签在gridview上打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!