我有一个Windows窗体应用程序,并且还使用SQL从我的数据库中获取数据。我的Windows应用程序中有一个绑定的checkListBox,我希望获得的主键(值)--中所有选中的项--。我意识到,在组合框中,它们有一个在方法'selectedValue‘中构建的方法,我想知道我们是否可以在checkListBox中通过在checkListBox中循环checkedItems并获得它的值来做同样的事情。
假设在我的db表中,我有:
EmployeeId Employee Name
1 Jimmy
2 Pam
3 Bob
4 Kobe我的绑定checkListBox显示了
[x]Jimmy
[x]Pam
[]Bob
[]Kobe可以使用sql获取checkedItem项的id。现在假设吉米和帕姆被检查了,我想得到他们的employeeId。我不知道该怎么做。我们会感谢你的帮助。
select * from employee_table where employeeId = '"+checkListBox.SelectedValue+"'或
foreach(var item = item.CheckedItems{
select * from employee_table where employeeId = '"items"';
}发布于 2015-10-02 12:37:39
您不需要再次进入数据库来检索项目的Id。
可以为包含Id和Name属性的项创建类,并重写ToString方法以返回要在CheckedListBox中显示的字符串。
public class ItemModel
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}然后,在加载数据时,可以选择输出并将其格式化为ItemModel,然后将这些ItemModels添加到CheckedListBox中:
private void Form_Load(object sender, EventArgs e)
{
var db = new TestDBEntities();
//Select items that you need and shape it to ItemModel
var list = db.Categories.Select(x => new ItemModel
{
Id = x.Id,
Name = x.Name
})
.ToList();
//We cast the list to object[] because AddRange method accept object[]
this.checkedListBox1.Items.AddRange(list.Cast<object>().ToArray());
}然后,当您需要了解选中项的Id时,可以简单地将每个选中项转换为ItemModel,并使用其Id属性:
private void button1_Click(object sender, EventArgs e)
{
this.checkedListBox1.CheckedItems.Cast<ItemModel>()
.ToList()
.ForEach(item =>
{
MessageBox.Show(string.Format("Id:{0}, Name:{1}", item.Id, item.Name));
});
}注:
如果您使用另一种方法连接到数据库,您可以简单地更改此代码以满足您的需求,例如,此代码使用ADO.Net对象将数据形状为ItemModel。
private void CheckedListBoxSample_Load(object sender, EventArgs e)
{
var connection = @"data source=(localdb)\v11.0;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;";
var command = "SELECT Id, Name From Categories";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var table = new DataTable();
dataAdapter.Fill(table);
var list = table.Rows.Cast<DataRow>()
.Select(row => new ItemModel
{
Id = row.Field<int>("Id"),
Name = row.Field<string>("Name")
})
.ToList();
this.checkedListBox1.Items.AddRange(list.Cast<object>().ToArray());
}发布于 2015-10-02 10:03:22
这样的东西可能会对你有帮助。基本上,它所做的就是构建一个参数化查询,然后使用SqlParameters添加所有选定的项。然后使用读取器,您可以解析每个返回的记录。下面的代码可能需要对其进行一些修改才能使用它,但是应该可以帮助您入门。
尽管我强烈建议使用像实体框架这样的ORM。使用ORM,您不必构建自己的查询,并且允许您使用强类型类与数据库“交谈”。
var query = "SELECT * FROM employee_table WHERE imployeeId IN (@ids)";
var ids = String.Join(","
MyCheckBoxList.Items
.Cast<ListItem>()
.Where(x => x.Selected)
.Select(x => x.Value);
using (var connection = new SqlConnection(myConnectionString))
{
connection.Open();
using(var command = new SqlCommand(query, connection)
{
command.Parameters.Add("ids", ids);
var reader = command.ExecuteReader();
while(reader.Read())
{
//get all the needed data from the reader
}
}
}https://stackoverflow.com/questions/32904212
复制相似问题