2017-05-30 66 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”事件。

相关问题