2017-05-30 70 views
0

我有一個綁定到數據庫字段的droplist數據。我有一個定義的值列表,我希望用戶從未來的選擇中進行選擇,但如果用戶打開舊記錄,我仍然希望用戶看到當前選擇。asp droplist無效,因爲它不存在於項目列表中

對於我droplist我已經加入數據綁定事件,並添加以下代碼:

protected void dbLeadConsultant_DataBinding(object sender, EventArgs e) 
{ 
     DropDownList dbLeadConsultant = (DropDownList)fvProjectMain.FindControl("dbLeadConsultant"); 

     try 
     { 
      dbLeadConsultant.DataBind(); 
     } 
     catch (ArgumentOutOfRangeException) 
     { 
      var dv = new DataView(); 
      var dt = new DataTable(); 

      dv = DSProjects.Select(DataSourceSelectArguments.Empty) as DataView; 
      dt = dv.ToTable(); 
      string strValue = dt.Rows[0]["LeadConsultant"].ToString(); 

      ListItem liValue = new ListItem(strValue, strValue); 

      dbLeadConsultant.Items.Add(liValue); 
      dbLeadConsultant.SelectedValue = "0"; 
     } 
    } 

這將停止「‘dbLeadConsultant’具有的SelectedValue這是無效的,因爲它沒有在項目列表中存在」錯誤,但我懷疑現在的問題是dbLeadConsultant_DataBinding現在會在調用DataBind的時候持續觸發。

如何停止此循環?

感謝

+0

爲什麼你甚至在'catch'中有所有的代碼?它看起來像通過在'DataBinding'方法中綁定來創建一個循環。如果不是那個錯誤,網站會崩潰。 – VDWWD

+0

是的,我明白了,如果我在另一時間嘗試綁定,我將不會選擇項目。我已經捕獲了所有的代碼,因爲只有當值無法設置時才需要運行它。否則,我不需要調用數據源。有什麼想法嗎? catch方法在網上提到了幾個處理空值的地方,但是我找不到用它來替換數據的例子,它具有綁定的麻煩。 – tommylux

回答

0

以下內容替換事件處理程序:

theDropDownList.DataBinding -= new EventHandler(PreventErrorOnbinding); 

我用來做它的動態最後的代碼是:

protected void PreventErrorOnbinding(object sender, EventArgs e) 
{ 

    DropDownList theDropDownList = (DropDownList)sender; 
    theDropDownList.DataBinding -= new EventHandler(PreventErrorOnbinding); 

    //Allow a combination of databind and appended data. 
    theDropDownList.AppendDataBoundItems = true; 

    //Tries to bind the data, if it doesn't exist, it will add it in the selection list. 
    try 
    { 
     theDropDownList.DataBind(); 
    } 
    catch (ArgumentOutOfRangeException) 
    { 
     var dv = new DataView(); 
     var dt = new DataTable(); 
     var ds = new SqlDataSource(); 

     //Uses the source data to add the missing value 
     dv = DSProjects.Select(DataSourceSelectArguments.Empty) as DataView; 
     dt = dv.ToTable(); 

     string strField = theDropDownList.ID.Substring(theDropDownList.ID.IndexOf("db")+2, theDropDownList.ID.Length - (theDropDownList.ID.IndexOf("db") + 2)); //Couldn't find a way to dynamically reference the DataBind fieldname. 
     string strValue = dt.Rows[0][strField].ToString(); 

     //Add the value pair. 
     ListItem liValue = new ListItem(strValue, strValue); 

     theDropDownList.Items.Add(liValue); 
     theDropDownList.SelectedValue = strValue; 
    } 
} 

我再加入PreventErrorOnbinding到 「OnDataBind」事件。

相關問題