2016-09-20 112 views
-1

我在aspx文件中寫一個函數在asp.net C#應用程序只有一個複選框在複選框列表檢查

 public void FillAfterClose(string Names) 
    { 

      string[] arrGroup = Names.ToString().Split(','); 

      foreach (object obj in arrGroup) 
      { 

       for (int i = 0; i < chklLicenceTypes.Items.Count; i++) 
       { 
        if (chklLicenceTypes.Items[i].Text == obj.ToString()) 
        { 
         chklLicenceTypes.Items[i].Selected = true; 
        } 
       } 
      } 
    } 

我通過代碼綁定與名稱和值對複選框

 <asp:CheckBoxList ID="chklLicenceTypes" RepeatDirection="Horizontal" AutoPostBack="false" 
CausesValidation="false" RepeatColumns="3" RepeatLayout="Table" runat="server"> 
    </asp:CheckBoxList> 

渲染頁面在瀏覽器中的CheckBoxList後充滿

  • 財產[]
  • 意外與健康[]
  • 生活[]
  • 因果[]
  • 無[]

如果字符串名稱中包含像 「財產保險,意外及健康,生活」 的值,則功能FillAfterClose只允許「財產和意外傷害」複選框啓用,其餘部分被忽略... 我希望「財產和意外,意外和健康,生活」複選框應該被選中。

回答

1

如果字符串恰好是:

var names="Property and Casualty, Accident and Health, Life"; 

那我就看到有是在分裂的結尾空格的問題。我會改變這一行:

string[] arrGroup = Names.ToString().Split(','); 

這將導致到:

new [] 
    { 
     "Property and Casualty", 
     " Accident and Health", 
     " Life" 
    }; 

這一行:

string[] arrGroup = names.Split(',').Select (s =>s.Trim()).ToArray(); 

這將導致到:

new [] 
    { 
     "Property and Casualty", 
     "Accident and Health", 
     "Life" 
    };