问题描述
|
我已经在列表框内的运行时生成了复选框,问题是我如何知道选中的复选框是什么?
我在C#中尝试了以下代码:
CheckBox box;
if ( box.Checked )
if ( box.IsChecked )
这是下面的代码:
public partial class Choose_Users
{
Service1Client C = new Service1Client();
Array a;
user_detail d;
String F_Name,L_Name;
CheckBox user = new CheckBox();
public Choose_Users()
{
InitializeComponent();
a = C.GetData();
for (int i = 0; i < a.Length; i++)
{
d = (user_detail)a.GetValue(i);
user.Name = d.First_name;
user.Content= d.First_name;
listBox1.Items.Add(user);
}
}
private void listBox1_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
List<user_detail> list = new List<user_detail>();
foreach(CheckBox box in this.listBox1.Items)
{
if (box.Checked // here my problem is
{
}
}
}
}
他们没有工作。有什么帮助吗?
解决方法
无论使用哪种编程语言,都需要保留对动态创建的复选框的引用。
您可以通过在任何本地方法和/或事件之外创建复选框来做到这一点:
CheckBox box;
然后在本地方法或事件中分配:
box = new CheckBox();
然后,您可以在代码和框中的其他任何位置访问box.IsChecked可以根据需要工作。
, 请用以下内容替换Choose_Users中的for循环。以下代码每次都会创建一个新的复选框对象。
for (int i = 0; i < a.Length; i++)
{
CheckBox user = new CheckBox();
d = (user_detail)a.GetValue(i);
user.Name = d.First_name;
user.Content= d.First_name;
listBox1.Items.Add(user);
}
关于checkstate,box.Checked是完美的。
让我知道这是否对您有帮助。
, 我们创建字符串selectedItem并将其分配给boxList的选定项,如下所示:
字符串selectedItem = Box.SelectedItem.Text;