論壇問題練習
把 DataGridViewTextBoxColumn 控件改為 DataGridViewComboBoxColumn 來呈現
namespace ChangeColControl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("Demo");
dt.Columns.Add("EmpNO", typeof(string));
dt.Columns.Add("EmpName", typeof(string));
dt.Columns.Add("WK_ID", typeof(string));
dt.Columns.Add("WK_Name", typeof(string));
dt.Rows.Add("201401", "蔡一", "W1", "會計");
dt.Rows.Add("201402", "鄭二", "W2", "資訊");
dt.Rows.Add("201403", "張三", "W3", "人事");
dt.Rows.Add("201404", "李四", "W4", "資材");
dt.Rows.Add("201405", "王五", "W5", "裝配");
dt.Constraints.Add("PK", dt.Columns["EmpNO"], true);
dgvData.DataSource = dt;
dgvData.AllowUserToAddRows = false;
}
private void btnChange_Click(object sender, EventArgs e)
{
chgControl();
}
private void chgControl()
{
// 判斷 ColWK_ID 和 ColWK_Name 欄位是否存在
if (dgvData.Columns.Contains("ColWK_ID") == false) return;
if (dgvData.Columns.Contains("ColWK_Name") == false) return;
// 移除部門相關的 DataGridViewTextBoxColumn 欄位
dgvData.Columns.Remove("ColWK_ID");
dgvData.Columns.Remove("ColWK_Name");
// 建立 DataGridViewComboBoxColumn 資料來源
DataTable dtWK_Name = new DataTable("dtWK_Name");
dtWK_Name.Columns.Add("WK_ID", typeof(string));
dtWK_Name.Columns.Add("WK_Name", typeof(string));
dtWK_Name.Rows.Add("W1", "會計");
dtWK_Name.Rows.Add("W2", "資訊");
dtWK_Name.Rows.Add("W3", "人事");
dtWK_Name.Rows.Add("W4", "資材");
dtWK_Name.Rows.Add("W5", "裝配");
// 建立 DataGridViewComboBoxColumn 欄位
DataGridViewComboBoxColumn cbo = new DataGridViewComboBoxColumn();
cbo.HeaderText = "部門";
cbo.Name = "ColWK_Name";
cbo.DataPropertyName = "WK_ID";
cbo.DataSource = dtWK_Name;
cbo.DisplayMember = "WK_Name";
cbo.ValueMember = "WK_ID";
// Insert 可以指定出入順序,Add 則是加在最後面
dgvData.Columns.Add(cbo);
dgvData.Refresh();
}
}
}
沒有留言:
張貼留言