在老外的一篇blog裡(http://fredrik.nsquared2.com/ViewPost.aspx?PostID=429),很好的一篇文章介紹了
asp.net 2.0中對gridview的一些基本操作,下面部分翻譯並小結之。
1 當要訪問gridview的當前行時,可以使用的事件為OnRowDataBound,
protected virtual void OnRowDataBound(GridViewRowEventArgs e);
在這個事件中,往往要關注的是rowtype和row state兩個屬性
其中,先來看下rowtype,
rowtype是a DataControlRowType 的集合,包括了
DataRow
EmptyDataRow
Footer,
Header
Pager
Seperator
比如下面的代碼檢查了當前是否處於gridview的header位置
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
}
}
如果要獲得當前的資料行是處於什麼樣的狀態,比如是編輯行,插入行,刪除行,交替行都可以獲得,則可以通過
rowstate屬性獲得
下面的圖可以清晰表現gridview的一些狀態
可以看到,比如當編輯某行的時候,rowstate的狀態是編輯,當選擇當選擇了某行時,狀態是selected,此外的也可以在圖上清晰的看到
2 訪問gridview的某一列
要注意的是,訪問時,可以用
e.Row.Cells[1]
去訪問gridview中的第2列,(第1列的預設是0下標)
如果是用了繫結資料行的話,比如
<asp:GridView ID="GridView1" …>
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" .../>
<asp:BoundField DataField="CompanyName" HeaderText="CustomerID" .../>
...
</Columns>
</asp:GridView>
那麼訪問某一列時,可以這樣
String customerId = e.Row.Cells[0].Text;
e.Row.Cells[0].Text = “New value for the first column”;
如果要改變某行的背景CSS,可以這樣
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].Text == “ANTON”)
{
e.Row.Cells[1].Style.Add(“background-color”,”red”);
}
}
}
再比如,如果已經將一個對象的集合綁定到一個gridview了,而且要訪問其中的每一行,可以這樣做
Customer customer = (Customer)e.Row.DataItem;
比如下面的代碼檢查每一行,如果發現ID為ANTON的話,則變顏色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Customer customer = (Customer)e.Row.DataItem;
if (customer.ID == “ANTON”)
{
e.Row.Cells[1].Style.Add(“background-color”,”red”);
}
}
}
如果是用模版列的話,而要訪問gridview中的某個控制項,可以用findcontrol
<asp:GridView ID="GridView1" ...>
<Columns>
<asp:BoundField DataField="CustomerID" ... />
<asp:TemplateField HeaderText="CompanyName" ...>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CompanyName") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
要獲得label1標籤,可以這樣,當然這前提是你準確知道要找的是第幾列
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label myLabel = (Label)e.Row.Cells[1].FindControl(“Label1”);
}
也可以這樣,用findcontrol
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label myLabel = (Label)e.Row.FindControl(“Label1”);
}
}