巧用DataGridView控制元件構建快速輸入體驗

iSQlServer發表於2010-09-30
    一個不錯的DataGridView資料視窗控制元件《DataGridView資料視窗控制元件開發方法及其原始碼提供下載》,這種控制元件在有些場合下,還是非常直觀的。因為,在一般要求客戶錄入資料的地方,一般有兩種途徑,其一是通過彈出一個新的視窗,在裡面列出各種需要輸入的要素,然後儲存的,如下圖所示;

1
 


  其二就是直接在DataGridView中直接輸入。這兩種方式各有優劣,本文介紹採用該控制元件實現第二種模式的資料資料。如下圖所示

1
 

  這種方式,直接通過在DataGridView中下拉選單或者文字框中輸入內容,每列的資料可以聯動或者做限制,實現使用者資料的約束及規範化。

  控制元件只要接受了DataTable的DataSource之後,會根據列的HeadText內容,顯示錶格的標題及內容,應用還是比較直觀方便的。

#div_code img{border:0px;}<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtprivate void BindGridViewData(DataTable dt, DataTable dtNoRelation)
        {
            organTable
= dt;
            noRelationTable
= dtNoRelation;

            DataGridView dataGridView1
= new DataGridView();
            this.groupBox1.Controls.Clear();
            this.groupBox1.Controls.Add(dataGridView1);
            dataGridView1.Dock
= DockStyle.Fill;
            dataGridView1.CellValueChanged
+=new DataGridViewCellEventHandler(organDataGridView_CellValueChanged);
            dataGridView1.UserDeletedRow
+= new DataGridViewRowEventHandler(organDataGridView_UserDeletedRow);

            dataGridView1.AutoGenerateColumns
= false;
            dataGridView1.Rows.Clear();
            dataGridView1.Columns.Clear();

            DataGridViewDataWindowColumn col1
= new DataGridViewDataWindowColumn();
            col1.HeaderText
= "機構程式碼";
            col1.Name
= "機構程式碼";  

            
//下拉選單的資料
            col1.DataSource
= GetDataTable(dtNoRelation);
            dataGridView1.Columns.Add(col1);

            DataGridViewTextBoxColumn col2
= new DataGridViewTextBoxColumn();
            col2.HeaderText
= "機構名稱";
            col2.Name
= "機構名稱";
            col2.Width
= 300;
            col2.ReadOnly
= true;
            dataGridView1.Columns.Add(col2);

            
if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    
string value = dr[0].ToString();
                    DataGridViewRow row
= new DataGridViewRow();
                    DataGridViewDataWindowCell cell
= new DataGridViewDataWindowCell();
                    cell.Value
= value;
                    row.Cells.Add(cell);
                    cell.DropDownHeight
= 400;
                    cell.DropDownWidth
= 300;

                    DataGridViewTextBoxCell cell2
= new DataGridViewTextBoxCell();
                    cell2.Value
= dr[1].ToString();
                    row.Cells.Add(cell2);
                    dataGridView1.Rows.Add(row);
                }
            }
        }

相關文章