1. 程式人生 > >DataSet、DataTable和DataGridView知識備忘

DataSet、DataTable和DataGridView知識備忘

datatable中,獲取第i行j列的單元格內容:
             string str = DataSet.Tables[0].Rows[i][j].ToString();
datagridview中,獲取第i行j列的單元格內容:
             string str =  DataGridview.Rows[i].Cells[j].Value.ToString();

DataGridview的  SelectionMode 屬性 設定為 FullRowSelect 之後,獲取指定單元格內容:
             string str = DataGridview.CurrentRow.Cells[j].Value.ToString() ;

DataGridView 單擊一次,即進入單元格編輯狀態:
             
this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;

datagridview 某一列自動適應列寬:
 
            this.dataGridView1.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
datagridview 中按 enter 鍵 游標跳至同列下一行 


datatable中新增行:

方法一:
 DataTable  tblDatas = new DataTable("Datas");

DataColumn dc = null;
dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
dc.AutoIncrement = true;//自動增加
dc.AutoIncrementSeed = 1;//起始為1
dc.AutoIncrementStep = 1;//步長為1
dc.AllowDBNull = false;//

dc = tblDatas.Columns.Add("Product", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("Version", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("Description", Type.GetType("System.String"));

DataRow newRow;
newRow = tblDatas.NewRow();
newRow["Product"] = "水果刀";
newRow["Version"] = "2.0";
newRow["Description"] = "打架專用";
tblDatas.Rows.Add(newRow);

newRow = tblDatas.NewRow();
newRow["Product"] = "摺疊凳";
newRow["Version"] = "3.0";
newRow["Description"] = "行走江湖七武器之一";
tblDatas.Rows.Add(newRow);

方法二:

 DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
tblDatas.Columns[0].AutoIncrement = true;
tblDatas.Columns[0].AutoIncrementSeed = 1;
tblDatas.Columns[0].AutoIncrementStep = 1;

tblDatas.Columns.Add("Product", Type.GetType("System.String"));
tblDatas.Columns.Add("Version", Type.GetType("System.String"));
tblDatas.Columns.Add("Description", Type.GetType("System.String"));

tblDatas.Rows.Add(new object[]{null,"a","b","c"});
tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });
tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });
tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });
tblDatas.Rows.Add(new object[] { null, "a", "b", "c" });