- <asp:TemplateField HeaderText="Tasks">
- <EditItemTemplate>
- <asp:ListBox ID="lbTasksToRole" runat="server" DataSourceID="sdsTasks" DataTextField="name" DataValueField="id" SelectionMode="Multiple"></asp:ListBox>
- <asp:HiddenField ID="hfTasksToRole" runat="server" Value='<%# Eval("task_ids") %>' />
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="lblTasksToRole" runat="server" Text='<%# Eval("tasks") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:CommandField HeaderText="Edit" ShowEditButton="True" CancelImageUrl="~/Images/Cancel.png" EditImageUrl="~/Images/edit.gif" UpdateImageUrl="~/Images/Update.png" ButtonType="Image" />
- protected void gvRoles_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowState.ToString().Contains("Edit"))
- {
- if (e.Row.FindControl("lbTasksToRole") != null)
- {
- ListBox lbTasksToRole = (ListBox) e.Row.FindControl("lbTasksToRole");
- HiddenField hfTasksToRole = (HiddenField) e.Row.FindControl("hfTasksToRole");
- string[] task_ids = hfTasksToRole.Value.Split(',');
- foreach (ListItem item in lbTasksToRole.Items)
- {
- foreach (string id in task_ids)
- {
- if (item.Value == id)
- {
- item.Selected = true;
- }
- }
- }
- }
- }
- }
開始我用
- e.Row.RowState == DataControlRowState.Edit
發現只綁定了基數row,偶數row失去綁定,設置一個斷點,會發現 前面的e.Row.RowState其實是Alernate | Edit,兩個狀態的組合,但是在DataControlRowState中間又沒有這樣的組合enum,所以用了字符串檢查Contain的笨方法,雖 然通過了,總覺得有更好的方法,如果讀者有什麼好建議可以告訴我,十分感謝
--------------------------------------------項目背景---------------------------------------------------------------
用ObjectDataSource或者SqlDataSource取好數據
然後用GridView智能綁定,在Edit columns選項頁,將Tasks列轉換成模板列,這樣在GridView右擊編輯模板列,
在itemTemplate中放一個Lable,在Text屬性中強寫 Text = '<%#
Eval("tasks") %>',
在editTemplate中放一個ListBox,爲了讓後來找到可以綁定的值,我就放了一個hiddent
filed <asp:HiddenField ID="hfTasksToRole" runat="server" Value='<%# Eval("task_ids") %>' />
P.S. 其實這裏沒有必要放HiddenField爲了存ListBox的值,在dataBound事件裏面,本來就有DataContainer對象,可以方便取當前的所有綁定值。
然後再調用上面的DataBound事件,通過判斷RowState來確定是點了Edit的imagebutton才觸發的修改和綁定。
- <asp:SqlDataSource ID="sdsRoles" runat="server" ConnectionString="<%$ ConnectionStrings:MISDbConnectionString %>"
- SelectCommand="SELECT id, name, description,dbo.uf_get_tasks_string_by_role_id(id) as tasks,dbo.uf_get_taskIds_string_by_role_id(id) as task_ids FROM Roles WHERE (audit_end IS NULL)"
- DeleteCommand="if exists(select * from rates where role_id = @id and audit_end is null) begin raiserror 50001 'This role is used by rates' return end update roles set audit_end = getDate() where id=@id and audit_end is null delete from role_task where role_id = @id" OnUpdating="sdsRoles_Updating" UpdateCommand="select 1">
- <DeleteParameters>
- <asp:Parameter Name="id" />
- </DeleteParameters>
- </asp:SqlDataSource>
- <asp:Panel ID="Panel2" runat="server" ScrollBars="Vertical" Height="300px" Width="500px">
- <asp:GridView ID="gvRoles" runat="server" AutoGenerateColumns="False" CellPadding="4"
- DataSourceID="sdsRoles" ForeColor="#333333" GridLines="None" AllowSorting="True" DataKeyNames="id" OnRowDataBound="gvRoles_RowDataBound" >
- <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Left" />
- <Columns>
- <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" ReadOnly="True" Visible="False" />
- <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" ReadOnly="True" />
- <asp:BoundField DataField="description" HeaderText="description" SortExpression="description" />
- <asp:TemplateField HeaderText="Tasks">
- <EditItemTemplate>
- <asp:ListBox ID="lbTasksToRole" runat="server" DataSourceID="sdsTasks" DataTextField="name" DataValueField="id" SelectionMode="Multiple"></asp:ListBox>
- <asp:HiddenField ID="hfTasksToRole" runat="server" Value='<%# Eval("task_ids") %>' />
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="lblTasksToRole" runat="server" Text='<%# Eval("tasks") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:CommandField HeaderText="Edit" ShowEditButton="True" CancelImageUrl="~/Images/Cancel.png"
- EditImageUrl="~/Images/edit.gif" UpdateImageUrl="~/Images/Update.png" ButtonType="Image" />
- <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ButtonType="Image"
- DeleteImageUrl="~/Images/delete.png" />
- </Columns>
- <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
- <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
- <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
- <EditRowStyle BackColor="#999999" VerticalAlign="Top" />
- <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
- <EmptyDataTemplate>
- No Tasks Found
- </EmptyDataTemplate>
- </asp:GridView>
- </asp:Panel>
--------------------------基礎知識---------------------------------------------
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”);
}
}