2014-01-16 24 views
1

我有一個CheckBoxList需要從由:分隔的SQL Server數據庫填充。CheckBoxList C#SQL Server數據庫中用「:」分隔的值

aspx頁面

<asp:CheckBoxList ID="chkTopics" runat="server" CssClass="ChkList"> 
<asp:ListItem Value="ABC">ABC</asp:ListItem> 
<asp:ListItem Value="D-E-F">D-E-F</asp:ListItem> 
<asp:ListItem Value="GHI">GHI</asp:ListItem> 
<asp:ListItem Value="J,K,L">J,K,L</asp:ListItem> 
<asp:ListItem Value="MNO">MNO</asp:ListItem> 
<asp:ListItem Value="PQR">PQR</asp:ListItem> 
</asp:CheckBoxList> 

上的.cs頁什麼,我如何得到的值:

SqlConnection conn = null; 
conn = new SqlConnection(conn_string); 

SqlCommand sqlCommand = new SqlCommand("aspnet_GetAnswers", conn); 
sqlCommand.CommandType = CommandType.StoredProcedure; 

conn.Open(); 

SqlDataReader rdr = sqlCommand.ExecuteReader(); 

if (rdr.Read()) 
{ 
    FirstName.Text = rdr.GetValue(2).ToString(); 
    LastName.Text = rdr.GetValue(3).ToString(); 
--> Putting the Code here to read the values and check the values that match. 
} 

rdr.Close(); 
conn.Close(); 
conn.Dispose(); 

從數據庫:

rdr.GetValue(9)的ToString ();

ABC:GHI:J,K,L:

+1

那麼,你有什麼問題:導致空項,可以使用StringSplitOptions.RemoveEmptyEntries選項刪除它們?你是說你不知道如何「分裂」一個「字符串」?這是一個暗示。 –

回答

0

喜歡這個

string str = GetValue(9).ToString().TrimEnd(':'); 
string[] strList = str.Split(':'); 


foreach (string s in strList) 
     { 
      foreach (ListItem item in chkTopics.Items) 
      { 
       if (item.Value == s) 
       { 
        item.Selected = true; 
        break; 
       } 

      } 

     } 
+0

但是其他的沒有出現。數據庫中的需要被選中。 – mrmcg

+0

檢查更新後的答案。我以爲你想從數據庫中顯示。 –

1

修剪最後一個冒號:

string trimmedString = optionsStringFromDb.TrimEnd(':'); 

獲取選項列表:

List<string> myOptions = trimmedString.Split(':').ToList(); 

然後填充您的CheckBoxList:

foreach (string option in myOptions) 
{ 
    chkTopics.Items.Add(new ListItem(option)); 
} 
+0

你在這裏展示的東西看起來不正確。 – mrmcg

+0

@mrmcg你是什麼意思「似乎不流」?你將必須更具體。 – nestedloop

+0

@mrmcg現在好了嗎? 'optionsStringFromDb只是一個通用的名字(用你持有查詢結果的字符串來代替) – nestedloop

1

您可以在結腸做一個string.Split(),然後創建每個LineItem並直接將它們添加到CheckBoxList

var result = rdr.GetValue(9).ToString(); 
chkTopics.Items.AddRange(result.Split(':') 
           .Select(x => new ListItem { Text = x, Value = x}) 
           .ToArray()); 

如果有一個機會,你就會有額外的冒號那會

.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries 
+0

檢查了這一個,它不會選擇任何東西。 – mrmcg

+0

在將它們添加到CheckBoxList之前嘗試存儲'result.Split(':')... ToArray()'在一個單獨的變量中,然後在該變量上放置一個斷點並仔細檢查該值是什麼(以及值的結果是)。 –

相關問題