2011-05-24 53 views
0

填充的GridView的下拉列表我使用代碼如下:問題從數據集

protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    MySqlConnection objMycon1 = new MySqlConnection(strProvider); 
    objMycon1.Open(); 
    MySqlCommand cmd1 = new MySqlCommand("select * from tblcountrynames",objMycon1); 
    MySqlDataAdapter da = new MySqlDataAdapter(cmd1); 
    DataSet ds = new DataSet(); 
    da.Fill(ds); 
    // DropDownList Control Object Created to bind the data dynamically with each 
    // nested DropDownlist control placed inside the template column of the GridView 
    // Control. 
    DropDownList drdList; 

    // foreach loop is used to loop through each row of GridView Control. 

    foreach (GridViewRow grdRow in grdViewCInfo.Rows) 
    {  
     // Nested DropDownList Control reference is passed to the DrdList object. 
     // This will allow you access the properties of dropdownlist placed 
     // inside the GridView Template column. 
     drdList = (DropDownList)(grdViewCInfo.Rows[grdRow.RowIndex].FindControl("ddlCountry")); 
     // DataBinding of nested DropDownList Control for each row of GridView Control. 
     drdList.DataSource = ds; 
     drdList.DataValueField = "ID"; 
     drdList.DataTextField = "Name"; 
     drdList.DataBind(); 
    } 
} 

它給出了一個錯誤爲:未設置爲一個對象的一個​​實例

對象引用。

在生產線drdList.DataSource = ds;

我該如何解決這個問題???

回答

0

嘗試指定在下面的代碼行的列:

drdList = (DropDownList)(grdViewCInfo.Rows[ grdRow.RowIndex ][ColumnIndex].FindControl("ddlCountry")); 

另一種選擇是遍歷列在另一個foreach

更多信息根據您的評論:

看起來你是ASP.NET新手,這就是爲什麼我推薦以下內容:

使用asp:TemplateColumn並將asp:DropDow EditTemplate中的nList。將DropDown掛鉤到SqlDataSource(或其他您希望使用的數據源)。

綁定將爲您處理。

我無法詳細說明看到您的ASP.NET代碼並瞭解您的需求的更多信息。

+0

我包括列索引,從而錯誤消失,但下拉列表顯示在編輯事件 – user755230 2011-05-24 06:06:54

+0

它不會在循環中爲我描繪出 – user755230 2011-05-24 06:15:33

+0

,如果它沒有在循環中去空,你是如何得到drdList.DataSource = ds的NullReferenceException的; ? – 2011-05-24 06:17:01

0

嘗試這個

DropDownList ddl; 
     int i = 0; 
     foreach (GridViewRow grdrow in grdmenu.Rows) 
     { 
    ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffer"); 
    ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["Offer"]); 
    ddl = (DropDownList)grdmenu.Rows[grdrow.RowIndex].FindControl("ddloffers"); 
    ddl.SelectedIndex = Convert.ToInt16(ds.Tables[0].Rows[i]["OfferType"]); 

      i++; 
      ddl.DataBind(); 
     } 
+2

有些解釋會很好。 – Raidri 2015-04-12 10:44:17