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

     }

}

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