2013年9月11日 星期三

[C#] 將 Datatable 與 DataGridView 綁在一起 、修改 DataTable 的內容


[C#] 將 Datatable 與 DataGridView 綁在一起
            //方式一
            DataTable dt = new DataTable("table");
            DataColumn colItem = new DataColumn("item", Type.GetType("System.String"));
            dt.Columns.Add(colItem);
            // Add five items.
            DataRow NewRow;
            for (int i = 0; i < 5; i++)
            {
                NewRow = dt.NewRow();
                NewRow["item"] = "Item " + i;
                dt.Rows.Add(NewRow);
            }
            // Change the values in the table.
            dt.Rows[0]["item"] = "cat";
            dt.Rows[1]["item"] = "dog";
            dt.AcceptChanges();

            //方式二
            //DataTable dt = new DataTable();
            //dt.Columns.Add(new DataColumn("Item", typeof(string)));
            //dt.Columns.Add(new DataColumn("Color", typeof(string)));
            //dt.Rows.Add(new string[] { "cat", "brown" });
            //dt.Rows.Add(new string[] { "dog", "white" });
            //原本的 dataGridView
            dataGridView1.DataSource = dt;
            //過濾後的 dataGridView
            DataView view = new DataView(dt);
            view.RowFilter = "Item='" + "dog" + "'";
            DataTable table = view.ToTable();
            dataGridView2.DataSource = table;
************************************************************************************
************************************************************************************
************************************************************************************
[C#] 自行修改 DataTable 的內容取代原有內容
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["trdataConnectionString"].ConnectionString);
            string query = "SELECT 顯示欄位1, 顯示欄位2, 顯示欄位3, '自訂欄位,這是說明內容......' AS '原本欄位', '' AS '自訂欄位1', '' AS '自訂欄位2' FROM table1 WHERE Date = @StartDate";
            //宣告欲自行修改的欄位 (不宣告修改會出錯)
            dt.Columns.Add(new DataColumn("自訂欄位1", typeof(string)));
            dt.Columns.Add(new DataColumn("自訂欄位2", typeof(string)));
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                conn.Open();
                cmd.Parameters.Add(new SqlParameter("@StartDate", StartDate));    //自訂的參數
                dt.Load(cmd.ExecuteReader());
                conn.Close();
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //設定自行修改的內容取代原有內容
                string[] sArrWord = dt.Rows[i]["原本欄位"].ToString().Trim().Split(',');
                dt.Rows[i]["自訂欄位1"] = sArrWord[0];
                dt.Rows[i]["自訂欄位2"] = sArrWord[1];
                dt.AcceptChanges();
            }
            GridView1.DataSourceID = null;
            GridView1.DataSource = dt;
            GridView1.DataBind();

沒有留言:

張貼留言