2017-05-30 4 views
0

データベースのフィールドにバインドされたドロップリストデータがあります。ユーザーに選択させたい値の定義済みのリストがありますが、ユーザーが古いレコードを開く場合でも、ユーザーには現在の選択肢が表示されます。アイテムのリストに存在しないため、aspドロップリストが無効です

私はDataBindingイベントを追加し、次のコードを追加している私のドロップリストについては

:これは「『dbLeadConsultantは』は項目のリストに存在しないため無効であるSelectedValueのを持っている」停止し

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_DataBindingがDataBindが呼び出されるまでに時間を掛け続けるという問題があると考えられます。

どのようにこのループを止めることができますか?

おかげ

+0

「キャッチ」にすべてのコードがあるのはなぜですか?そして、あなたは 'DataBinding'メソッドでバインドしてループを作成しているようです。そのエラーがなければ、サイトはクラッシュします。 – VDWWD

+0

はい、私は別の時間にバインドしようとすると、選択肢にないアイテムを手に入れることができます。値を設定できない場合は、実行する必要があるだけで、すべてのコードをキャッチしています。それ以外の場合は、データソースを呼び出す必要はありません。何かご意見は? catchメソッドは、nullを処理するためにオンラインでいくつかの場所が記載されていますが、問題のあるバインディングを持つデータで置き換えるサンプルが見つかりません。 – 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; 
    } 
} 

私はその後、「OnDataBind」にPreventErrorOnbindingを追加イベント。

関連する問題