- <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”);
}
}