2014-01-06 80 views
0

我是一個網格視圖,我可以編輯,更新,刪除。我可以手動添加一個下拉列表並將選定的值填充正確,但我希望能夠在編輯時從數據庫中填充下拉列表(並正確顯示選定的值)。c#在網格視圖下拉列表

我已經嘗試了一堆搜索/選項,但找不到一種方法使其工作。

我的代碼如下:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      PopulateData(); 
      lblMessage.Text = ""; 
     } 

     string sSQL = ""; 

     // populate drop downs 
     sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText 
      FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK) 
      WHERE ErrorType = 'Category' 
      "; 
     //ORDER BY OrderBy, ErrorDescription"; 

     new DatabaseConnection().PopulateListBoxFromDB(sSQL, "", lstNewResolutionCategory); 


     sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText 
      FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK) 
      WHERE ErrorType = 'Severity' 
      "; 
     //ORDER BY OrderBy, ErrorDescription"; 

     new DatabaseConnection().PopulateListBoxFromDB(sSQL, "", lstNewResolutionSeverity); 


    }//end page load 


    protected void DeleteRow(object sender, GridViewDeleteEventArgs e) 
    { 

     var ResolutionsID = GridView1.DataKeys[e.RowIndex].Value; 

     GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow; 

     string sSQL = "Delete from BabelFish.dbo.Resolutions where ResolutionsID = @ResolutionsID"; 

     SqlCommand sCommand = new SqlCommand(sSQL); 

     sCommand.Parameters.AddWithValue("@ResolutionsID", ResolutionsID); 

     // run delete 
     new DatabaseConnection().RSExecute(sCommand); 

     lblMessage.Text = "Record deleted successfully !"; 

     GridView1.EditIndex = -1; 

     this.PopulateData(); 

    } 




    protected void UpdateRow(object sender, GridViewUpdateEventArgs e) 
    { 

     var ResolutionsID = GridView1.DataKeys[e.RowIndex].Value; 

     GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow; 

     TextBox txtResolutionDescription = row.FindControl("txtResolutionDescription") as TextBox; 
     DropDownList drpErrorCategoryID = row.FindControl("ErrorCategory") as DropDownList; 


     string sSQL = @"Update BabelFish.dbo.Resolutions set 
        ResolutionDescription = @ResolutionDescription, 
        UserIDSolved = ISNULL(BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(@UserIDSolved), BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(REPLACE(@UserIDSolved, '-', ''))), 
        DateTimeSolved = ISNULL(DateTimeSolved, GetDate())       
        where ResolutionsID = @ResolutionsID"; 

     SqlCommand sCommand = new SqlCommand(sSQL); 

     sCommand.Parameters.AddWithValue("@ResolutionDescription", txtResolutionDescription.Text.Trim()); 
     sCommand.Parameters.AddWithValue("@ResolutionsID", ResolutionsID); 
     sCommand.Parameters.AddWithValue("@UserIDSolved", UserID); 

     // run update 
     new DatabaseConnection().RSExecute(sCommand); 


     lblMessage.Text = "Record updated successfully !"; 

     GridView1.EditIndex = -1; 

     this.PopulateData(); 

    } 




    private void PopulateData() 
    { 
     string sSQL = @"SELECT 
       ResolutionsID, ErrorTableID, BabelFish.dbo.fn_GetUserNameFromTeamMemberTable(UserIDSolved) as UserIDSolved, 
       DateTimeSolved, ResolutionDescription, ResolutionCategory, ResolutionSeverity, IsActive 
       FROM BabelFish.dbo.Resolutions (NOLOCK) 
       Where ErrorTableID = '" + ErrorTableID + "'"; 

     DataTable dt = DatabaseAccessing.DatabaseConnection.GetDataTable(sSQL); 

     // only do if more then 1 row exists 
     if (dt.Rows.Count > 0) 
     { 
      GridView1.DataSource = dt; 

      GridView1.DataBind(); 
     } 
     else 
     { 
      lblMessage.Text = "No Rows Exist."; 
     } 




    } 


    protected void AddRow(object sender, EventArgs e) 
    { 
     // get values to add to database 
     string txtResolutionDescription = txtNewResolutionDescription.Text.ToString(); 

     string lstCategoryID = lstNewResolutionCategory.SelectedValue; 
     string lstSeverityID = lstNewResolutionSeverity.SelectedValue; 

     string sSQL = @"INSERT INTO BabelFish.dbo.Resolutions (
      ErrorTableID, UserIDSolved, DateTimeSolved, ResolutionDescription, 
      ResolutionCategory, ResolutionSeverity, IsActive 
     ) 

     VALUES (
      @ErrorTableID, ISNULL(BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(@UserIDSolved), BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(REPLACE(@UserIDSolved, '-', ''))), 
      GetDate(), @ResolutionDescription, 
      @ResolutionCategory, @ResolutionSeverity, 1 
     )"; 


     SqlCommand sCommand = new SqlCommand(sSQL); 

     sCommand.Parameters.AddWithValue("@ErrorTableID", ErrorTableID); 
     sCommand.Parameters.AddWithValue("@UserIDSolved", UserID); 
     sCommand.Parameters.AddWithValue("@ResolutionDescription", txtResolutionDescription); 
     sCommand.Parameters.AddWithValue("@ResolutionCategory", lstCategoryID); 
     sCommand.Parameters.AddWithValue("@ResolutionSeverity", lstSeverityID); 


     // run update 
     new DatabaseConnection().RSExecute(sCommand); 


     lblMessage.Text = "Record successfully added!"; 

     GridView1.EditIndex = -1; 

     this.PopulateData(); 
    } 


    protected void EditRow(object sender, GridViewEditEventArgs e) 
    { 
     GridView1.EditIndex = e.NewEditIndex; 

     this.PopulateData(); 

     /* 
     //not working, ddl is NULL 
     var ddl = (DropDownList)GridView1.FindControl("selResolutionSeverity"); 

     string sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText 
      FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK) 
      WHERE ErrorType = 'Severity' "; 


     DataSet DS = new DatabaseAccessing.DatabaseConnection().DS(sSQL); 

     ddl.DataSource = DS; 
     ddl.DataTextField = "DisplayText"; 
     ddl.DataValueField = "Value"; 
     ddl.DataBind(); 
     ddl.Items.Insert(0, new ListItem("-- Select --", "0")); 
     * */ 
    } 



    protected void CancelEditRow(object sender, GridViewCancelEditEventArgs e) 
    { 
     GridView1.EditIndex = -1; 
     this.PopulateData(); 
    } 


    protected void ChangePage(object sender, GridViewPageEventArgs e) 
    { 

     GridView1.PageIndex = e.NewPageIndex; 
     this.PopulateData(); 

    } 



    <asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" /> 

    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" 
     AutoGenerateColumns="false" 
     Width="100%" 
     OnRowEditing="EditRow" 
     OnRowCancelingEdit="CancelEditRow" 
     OnRowUpdating="UpdateRow" 
     DataKeyNames="ResolutionsID" 
     OnRowDeleting="DeleteRow" 
     AllowPaging="true" 
     PageSize="50" 
     OnPageIndexChanging="ChangePage"    

     > 

    <Columns> 

     <asp:TemplateField HeaderText="Edit"> 

      <ItemTemplate> 
       <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" /> 
      </ItemTemplate> 

      <EditItemTemplate> 

       <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" /> 

       <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" /> 

      </EditItemTemplate> 

     </asp:TemplateField> 


     <asp:BoundField HeaderText="ResolutionsID" DataField="ResolutionsID" ReadOnly="true" /> 

     <asp:TemplateField HeaderText="ResolutionDescription"> 
      <ItemTemplate><%# Eval("ResolutionDescription")%></ItemTemplate> 

      <EditItemTemplate> 
       <asp:TextBox ID="txtResolutionDescription" runat="server" Text='<%# Eval("ResolutionDescription") %>'/> 
      </EditItemTemplate> 
     </asp:TemplateField> 

     <asp:BoundField HeaderText="UserIDSolved" DataField="UserIDSolved" ReadOnly="true" /> 

     <asp:TemplateField HeaderText="Category"> 
      <ItemTemplate> 
       <%# Eval("ResolutionCategory")%> 
      </ItemTemplate> 

      <HeaderStyle HorizontalAlign="Left" /> 
       <EditItemTemplate> 
        <asp:DropDownList ID="selResolutionCategory" runat="server" SelectedValue='<%# Eval("ResolutionCategory") %>'>   
         <asp:ListItem Text="-- Select One --" Value="0" /> 
         <asp:ListItem Text="cat1" Value="1" /> 
         <asp:ListItem Text="cat2" Value="2" />   
        </asp:DropDownList> 
       </EditItemTemplate> 
     </asp:TemplateField> 


     <asp:TemplateField HeaderText="Severity"> 
      <ItemTemplate> 
       <%# Eval("ResolutionSeverity")%> 
      </ItemTemplate> 

      <HeaderStyle HorizontalAlign="Left" /> 
       <EditItemTemplate> 
        <asp:DropDownList ID="selResolutionSeverity" runat="server">          
        </asp:DropDownList> 
       </EditItemTemplate> 
     </asp:TemplateField> 


     <asp:TemplateField HeaderText="Delete?"> 
      <ItemTemplate> 
       <span onclick="return confirm('Are you sure to delete?')"> 
        <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" /> 
       </span> 
      </ItemTemplate> 

     </asp:TemplateField> 


    </Columns> 

    <AlternatingRowStyle BackColor="White" /> 

    <EditRowStyle BackColor="#efefef" /> 

    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> 

    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> 

    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> 

    <RowStyle BackColor="#EFF3FB" /> 

    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> 

    <SortedAscendingCellStyle BackColor="#F5F7FB" /> 

    <SortedAscendingHeaderStyle BackColor="#6D95E1" /> 

    <SortedDescendingCellStyle BackColor="#E9EBEF" /> 

    <SortedDescendingHeaderStyle BackColor="#4870BE" /> 

    </asp:GridView> 

回答

2

你將要使用OnRowDataBound。這裏是我如何在我的GridView中填充我的下拉列表中的一個示例。

protected void gvVehicle_OnRowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     foreach (GridViewRow gvr in gvVehicleTEMP.Rows) 
     { 
      DropDownList ddlLocation = ((DropDownList)gvr.FindControl("ddlLocation")); 
      Label lblLocationLabel = ((Label)gvr.FindControl("lblLocationLabel")); 

      conn.Close(); 
      conn.Open(); 

      SqlCommand cmdLocationNames = new SqlCommand("SELECT Name FROM Billers WHERE Store = '" + 1 + "' ORDER BY Name ASC", conn); 
      List<string> internalLocationsList = new List<string>(); 

      using (SqlDataReader reader = cmdLocationNames.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        string interlocations = reader.GetString(0); 
        internalLocationsList.Add(interlocations); 
       } 
       foreach (string locname in internalLocationsList) 
       { 
        ddlLocation.Items.Add(new ListItem(locname)); 
        conn.Close(); 
       } 
       conn.Close(); 
      } 

      conn.Close(); 

     } 

    //EDIT: if (lblLocationLabel.Text.Length > 0) 
      { 
       ddlLocation.SelectedValue = lblLocationLabel.Text; 
      } 
    } 

因此,我使用了一個SqlDataReader,然後將「Billers」添加到列表中。一旦發生這種情況,我將listItems添加到下拉列表中。

我必須做什麼,以正確選擇被綁定的文本標籤,然後說..

ddlLocation.SelectedValue = lblLabelLocation.Text;

不要忘記把OnRowDataBound放到你的gridview屬性中。我希望這有幫助。

編輯:

這就是我做到的。我使用if語句來檢查標籤的文本長度是否爲空(我的下拉列表中有一個空白字段),如果它有文本,則選擇或顯示值..我在上面做了編輯,但在這裏它再次。

protected void gvVehicle_OnRowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     foreach (GridViewRow gvr in gvVehicleTEMP.Rows) 
     { 
      DropDownList ddlLocation = ((DropDownList)gvr.FindControl("ddlLocation")); 
      Label lblLocationLabel = ((Label)gvr.FindControl("lblLocationLabel")); //add this line to find the label 

      conn.Close(); 
      conn.Open(); 

      SqlCommand cmdLocationNames = new SqlCommand("SELECT Name FROM Billers WHERE Store = '" + 1 + "' ORDER BY Name ASC", conn); 
      List<string> internalLocationsList = new List<string>(); 

      using (SqlDataReader reader = cmdLocationNames.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        string interlocations = reader.GetString(0); 
        internalLocationsList.Add(interlocations); 
       } 
       foreach (string locname in internalLocationsList) 
       { 
        ddlLocation.Items.Add(new ListItem(locname)); 
        conn.Close(); 
       } 
       conn.Close(); 
      } 

      conn.Close(); 

     } 

     if (lblLocationLabel.Text.Length > 0)//Added if statement 
      { 
       ddlLocation.SelectedValue = lblLocationLabel.Text; 
      } 
    } 

我使用像這樣的templatefield。

<asp:TemplateField HeaderText="Location" SortExpression="Received"> 
      <ItemTemplate> 
        <asp:DropDownList ID="ddlLocation" runat="server" AutoPostBack="false"> 
        </asp:DropDownList> 
        <asp:Label ID="lblLocationLabel" runat="server" Text='<%# Bind("Location") %>' Visible="false"></asp:Label> 
           <font size="2">Received On: </font> 
      </ItemTemplate> 
      <HeaderStyle Width="200px" /> 
</asp:TemplateField> 

我希望這可以把它弄清楚一點。

+0

我得到它的工作做的事情類似於你上面的,但當我嘗試設置SelectedValue ='<%#Eval(「ResolutionCategory」)%>'我得到錯誤:''selResolutionCategory'有一個SelectedValue是無效的,因爲它不存在於列表中項目「。但我知道它通過查詢數據庫確實沒有辦法像上面這樣做(這適用於文本框) – Brad

+0

不是我所知道的。有同樣的問題。這就是爲什麼我做了一個標籤 - 將它設置爲false的可見屬性,然後使用ddlDropDownList.SelectedValue = lblLabel.Text;我厭倦了它,並知道這會工作。 – Humpy

+0

我如何使用上面的完整代碼做到這一點?我正在使用綁定字段和模板字段進行編輯。 – Brad

0

有幾個問題在這裏:

  1. 你似乎不與ID selResolutionSeverity
  2. 你的FindControl(被填充的DropDownList)在家長控制水平是不行的(你需要首先找到正在更新的行)

我建議你使用數據綁定簡化程序。如果您能夠爲嚴重級創建數據源(例如SqlDataSource),那麼您不需要在代碼後面放置任何特定的邏輯。以下示例假定您的頁面中有一個SqlDataSource,名爲dsSeverities。如果你不想走這條路線,那麼你可以在RowDataBound事件處理程序中填充DropDownList。

<asp:TemplateField HeaderText="Severity"> 
<HeaderStyle HorizontalAlign="Left" /> 
<ItemTemplate> 
    <%# Eval("ResolutionSeverity")%> 
</ItemTemplate> 

<EditItemTemplate> 
    <asp:DropDownList ID="selResolutionSeverity" runat="server" 
    DataSourceID="dsSeverities" 
    DataTextField="Description" 
    DataValueField="ID" 
    SelectedValue='<%# Bind("ResolutionSeverity") %>' /> 
</EditItemTemplate> 
</asp:TemplateField> 
0

你必須找到在GridViewRow這是編輯模式GridViewOnRowDataBound事件DropDownList

這裏是你如何能做到這一點:

在標記添加一個方法來GridView的OnDtatBound。 :

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" 
    ... ... ... 
    OnRowDataBound="GridView1_RowDataBound" > 
代碼

現在寫您的GridView1_RowDataBound方法寫代碼(我會強烈建議使用參數化查詢替換查詢字符串,以防止可能的SQL注入):

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) 
{ 
    //Make sure the row is in edit mode to find controls in EditItemTemlates 
    if ((e.Row.RowType == DataControlRowType.DataRow) && ((e.Row.RowState & DataControlRowState.Edit) > 0)) 
    { 

     var ddl = GridView1.FindControl("selResolutionSeverity") as DropDownList; 
     if (ddl != null) 
     { 

      // Consider using parameterized query to prevent possible sql injection 
      string sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText 
          FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK) 
          WHERE ErrorType = 'Severity' "; 

      DataSet DS = new DatabaseAccessing.DatabaseConnection().DS(sSQL); 
      ddl.DataSource = DS; 
      ddl.DataTextField = "DisplayText"; 
      ddl.DataValueField = "Value"; 
      ddl.DataBind(); 
      ddl.Items.Insert(0, new ListItem("-- Select --", "0")); 
     } 
    } 
}