출처 : 본인


2016/11/21 - [프로그램 자료/Visual C#] - 데이터그리드뷰(DataGridView)를 이쁘게 바꿔보자



해당 프로젝트에서는 Winform에 DataGridView 1개와 Button 1개가 필요하다.


formDataGridView.cs

public partial class formDataGridView : Form

{

    public formDataGridView()

    {

        InitializeComponent();

    }

    DataTable dt = new DataTable();

    BindingSource bs = new BindingSource();

    Dictionary<Int32, string> cbDs =

                new Dictionary<Int32, string> {

                {65, "A" }

                ,{66, "B" }

                ,{67, "C" }

                ,{68, "D" }

                ,{69, "E" }

                ,{70, "F" }

        };

 

    private void formDataGridView_Load(object sender, EventArgs e)

    {

        dt.Columns.Add("Key", Type.GetType("System.String"));

        dt.Columns.Add("Value", Type.GetType("System.Int32"));

        for (int i = 65; i < 70; i++)

        {

            DataRow r = dt.NewRow();

            r["Key"] = "Ascii " + i.ToString();

            r["Value"] = i;

            dt.Rows.Add(r);

        }

 

        dataGridView1.DataSource = bs;

        bs.DataSource = dt;

 

        //datagridview combo column databinding

        DataGridViewComboBoxColumn cbA = this.dataGridView1.Columns["Column2"] as DataGridViewComboBoxColumn;

        cbA.DataSource = new BindingSource(cbDs, null);

        cbA.DisplayMember = "Value";

        cbA.ValueMember = "Key";

    }

 

    private void button1_Click(object sender, EventArgs e)

    {

        foreach (DataRow dr in dt.Rows)

        {

            Console.WriteLine(dr["Key"].ToString() + " | " + dr["Value"].ToString());

        }

    }

}

 


formDataGridView.cs[디자인]


dataGridView1  -> Colums 속성


데이터 바인딩 시 가장 중요한건 [데이터] -> [DataPropertyName] 부분 정의


이렇게 바인딩한 DataTable을 Row 단위로 수정하고 싶을 때는 아래와 같이 사용할 수 있다.

public DataRow GetDataRow(DataGridViewRow dgvr)

{

    DataRow result = null;

    try

    {

        result = (dgvr.DataBoundItem as DataRowView).Row;

    }

    catch (Exception)

    {

    }

    return result;

}


선택된 행들을 반환

foreach (DataGridViewRow dr in dgv.SelectedRows)

{

    DataRow r = GetDataRow(dr);

    r.Delete();

}


현재 선택된 행을 반환

DataGridViewRow dgvr = dgvAssetBatch.CurrentRow;

DataRow r = GetDataRow(dgvr);


이렇게 바인딩한 datatable에 대하여 변경을 하고 변경내용을 accept 하려면 아래와 같이 하면 된다

bs.RaiseListChangedEvents = false

dt.AcceptChanges();

bs.RaiseListChangedEvents = true;


datagridview가 master와 detail이 있다고 가정할 때 master를 갱신 후 detail을 다시 설정해야 하는 이슈가 있다면

아래와 같이 해당 컨티션에 해당하는 row와 cell을 선택해주고, 

selectionChange 이벤트를 발생시킨다

if (dtMaster.Rows.Count > 0)

{

    dgvAssetBatch.ClearSelection();

    foreach (DataGridViewRow row in dgvAssetBatch.Rows)

    {

        if (Convert.ToInt32(row.Cells["ALLOT_ID"].Value) == curAllotID) {

            row.Selected = true;

            row.Cells["ALLOT_NO"].Selected = true;

            dgvAssetBatch_SelectionChanged(this, new EventArgs());

        }

    }

}


Posted by motolies
,