DataGridView的某列是ComBox列怎么绑定数据
我拖了一个DataGridView控件,里面有一列ComBoxColumn列,是跟DataGridView一起绑定数据源,还是可以单独这列绑定数据源,如果可以怎么绑定。在线等。
[解决办法]
1:首先combox列依然是和数据库中对应的列绑定
2:我们需要设置combox列的ItemSource属性,并设置其其他绑定属性(DisplayMember,ValueMember)
3:之后,combox列会根据数据库中得到的值自动设定其显示方式
以下是一个实例,combox列显示书籍的是否可借状态,楼主可参考
private void btn_Search_Click(object sender, EventArgs e)
{
string sql = GetCondition();
DataTable dt=PubData.GetData(sql);
//显示方式
SetDataGridViewStyle();
dataGridView1.DataSource = dt;
}
/// <summary>
/// 拼接条件
/// </summary>
/// <returns></returns>
private string GetCondition()
{
StringBuilder sb = new StringBuilder();
sb.Append("select BookName,Author,Press,Qty,Status From BookInfo where");
sb.Append(" BookName like '%"+txt_BookName.Text.Trim()+"%'");
sb.Append(" and Author like '%"+txt_Author.Text.Trim()+"%'");
sb.Append(" and Press like '%"+txt_Press.Text.Trim()+"%'");
return sb.ToString();
}
/// <summary>
/// 设置DataGridView列
/// </summary>
private void SetDataGridViewStyle()
{
DataGridViewTextBoxColumn columns = new DataGridViewTextBoxColumn();
columns.Name = "BookName";
columns.HeaderText = "书籍名称";
columns.DataPropertyName = "BookName";
columns.Width = 100;
this.dataGridView1.Columns.Add(columns);
columns = new DataGridViewTextBoxColumn();
columns.Name = "Author";
columns.HeaderText = "作者";
columns.DataPropertyName = "Author";
columns.Width = 60;
this.dataGridView1.Columns.Add(columns);
columns = new DataGridViewTextBoxColumn();
columns.Name = "Press";
columns.HeaderText = "出版社";
columns.DataPropertyName = "Press";
columns.Width = 105;
this.dataGridView1.Columns.Add(columns);
columns = new DataGridViewTextBoxColumn();
columns.Name = "Qty";
columns.HeaderText = "数量";
columns.DataPropertyName = "Qty";
columns.Width = 60;
this.dataGridView1.Columns.Add(columns);
//这里为DataGridView添加了一个combox列
//依然绑定数据库中对应的列
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Name = "Status";
column.DataPropertyName = "Status";
column.HeaderText = "状态";
column.Width = 80;
this.dataGridView1.Columns.Add(column);
column.DataSource = GetData(); //这里需要设置一下combox的itemsource,以便combox根据数据库中对应的值自动显示信息
column.DisplayMember = "LendStatus";
column.ValueMember = "Status";
}
/// <summary>
/// 获得Combox的填充资源信息
/// </summary>
/// <returns></returns>
private DataTable GetData()
{
string sql = "select distinct status,case when Status=1 then '可借' else '不可借' end LendStatus from bookinfo";
DataTable dt = PubData.GetData(sql);
return dt;
}
public class PubData
{
public const string connectionString = "Data Source=.;Initial Catalog=BirthdayRemind;Integrated Security=True";
/// <summary>
/// 返回信息
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable GetData(string sql)
{
DataTable dt = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlDataAdapter sda=new SqlDataAdapter(sql,conn);
DataSet ds=new DataSet();
sda.Fill(ds);
if (ds.Tables.Count > 0)
dt = ds.Tables[0];
}
return dt;
}
}