gridview中使用edit命令显示EditItemTemplateColumn,绑定Listbox的值问题

页面代码
  1.  <asp:TemplateField HeaderText="Tasks">
  2.       <EditItemTemplate>
  3.            <asp:ListBox ID="lbTasksToRole" runat="server"  DataSourceID="sdsTasks" DataTextField="name" DataValueField="id" SelectionMode="Multiple"></asp:ListBox>
  4.            <asp:HiddenField ID="hfTasksToRole" runat="server" Value='<%# Eval("task_ids") %>' />
  5.       </EditItemTemplate>
  6.       <ItemTemplate>
  7.            <asp:Label ID="lblTasksToRole" runat="server" Text='<%# Eval("tasks") %>'></asp:Label>
  8.       </ItemTemplate>
  9.  </asp:TemplateField>
  10.   
  11.  <asp:CommandField HeaderText="Edit" ShowEditButton="True" CancelImageUrl="~/Images/Cancel.png" EditImageUrl="~/Images/edit.gif" UpdateImageUrl="~/Images/Update.png" ButtonType="Image" />
后台C#代码


  1.  protected void gvRoles_RowDataBound(object sender, GridViewRowEventArgs e)
  2.      {
  3.          if (e.Row.RowState.ToString().Contains("Edit"))
  4.          {
  5.              if (e.Row.FindControl("lbTasksToRole") != null)
  6.              {
  7.                  ListBox lbTasksToRole = (ListBox) e.Row.FindControl("lbTasksToRole");
  8.                  HiddenField hfTasksToRole = (HiddenField) e.Row.FindControl("hfTasksToRole");
  9.                  string[] task_ids = hfTasksToRole.Value.Split(',');
  10.                  foreach (ListItem item in lbTasksToRole.Items)
  11.                  {
  12.                      foreach (string id in task_ids)
  13.                      {
  14.                          if (item.Value == id)
  15.                          {
  16.                              item.Selected = true;
  17.                          }
  18.                      }
  19.                  }
  20.              }
  21.          }
  22.      }

开始我用

  1. 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来确定是点了Editimagebutton才触发的修改和绑定。







  1. <asp:SqlDataSource ID="sdsRoles" runat="server" ConnectionString="<%$ ConnectionStrings:MISDbConnectionString %>"
  2.                             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)" 
  3.                             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">
  4.                             <DeleteParameters>
  5.                                 <asp:Parameter Name="id" />
  6.                             </DeleteParameters>
  7.                         </asp:SqlDataSource>
  8.                         <asp:Panel ID="Panel2" runat="server" ScrollBars="Vertical" Height="300px" Width="500px">
  9.                             <asp:GridView ID="gvRoles" runat="server" AutoGenerateColumns="False" CellPadding="4"
  10.                                 DataSourceID="sdsRoles" ForeColor="#333333" GridLines="None" AllowSorting="True" DataKeyNames="id" OnRowDataBound="gvRoles_RowDataBound" >
  11.                                 <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  12.                                 <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Left" />
  13.                                 <Columns>
  14.                                     <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" ReadOnly="True" Visible="False" />
  15.                                     <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" ReadOnly="True" />
  16.                                     <asp:BoundField DataField="description" HeaderText="description" SortExpression="description" />
  17.                                     <asp:TemplateField HeaderText="Tasks">
  18.                                         <EditItemTemplate>
  19.                                             <asp:ListBox ID="lbTasksToRole" runat="server"  DataSourceID="sdsTasks" DataTextField="name" DataValueField="id" SelectionMode="Multiple"></asp:ListBox>
  20.                                             <asp:HiddenField ID="hfTasksToRole" runat="server" Value='<%# Eval("task_ids") %>' />
  21.                                         </EditItemTemplate>
  22.                                         <ItemTemplate>
  23.                                             <asp:Label ID="lblTasksToRole" runat="server" Text='<%# Eval("tasks") %>'></asp:Label>
  24.                                         </ItemTemplate>
  25.                                     </asp:TemplateField>
  26.                                     <asp:CommandField HeaderText="Edit" ShowEditButton="True" CancelImageUrl="~/Images/Cancel.png"
  27.                                         EditImageUrl="~/Images/edit.gif" UpdateImageUrl="~/Images/Update.png" ButtonType="Image" />
  28.                                     <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ButtonType="Image"
  29.                                         DeleteImageUrl="~/Images/delete.png" />
  30.                                 </Columns>
  31.                                 <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
  32.                                 <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  33.                                 <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
  34.                                 <EditRowStyle BackColor="#999999" VerticalAlign="Top" />
  35.                                 <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
  36.                                 <EmptyDataTemplate>
  37.                                     No Tasks Found
  38.                                 </EmptyDataTemplate>
  39.                             </asp:GridView>
  40.                         </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”);

     }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章