2010年7月5日 星期一

DataGridViewComboBoxColumn的使用 (高招)

原出處

注意事项:
.注意其ValueMember的DataType与DataPropertyName对应的列的DataType要相同,他不会为你做类型转换的。
2.编程设置显示样式时注意一定要在设置DataSource之前设置DataGridViewComboBoxColumn的DataSource等属性。
------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Sys
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void Form3_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AutoGenerateColumns = false;

using (SqlConnection sqlconn = new SqlConnection("server=.;uid=sa;pwd=sa;database=xx"))
{
string sql1 = @"select userid,fullname,a.[description],b.ugroupid
from users a left outer join usergroup b
on a.grade=b.ugroupid";
string sql2 = "select distinct ugroupid,[description] from usergroup";

DataGridViewComboBoxColumn dgvComboBoxColumn = dataGridView1.Columns["grade"] as DataGridViewComboBoxColumn;
dgvComboBoxColumn.DataPropertyName = "ugroupid";
dgvComboBoxColumn.DataSource = GetTable(sql2).DefaultView;//必须在设置dataGridView1的DataSource的属性前设置
dgvComboBoxColumn.DisplayMember = "description";
dgvComboBoxColumn.ValueMember = "ugroupid";

dataGridView1.DataSource = GetTable(sql1).DefaultView;//一定要在dgvComboBoxColumn的DataSource后设置
}
}

private DataTable GetTable(string sql)
{
using (SqlConnection sqlconn = new SqlConnection("server=.;uid=sa;pwd=yuling1310;database=smls"))
{
DataTable dt = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter(sql, sqlconn);
sqlda.Fill(dt);
return dt;
}
}
}
}

沒有留言:

張貼留言