技术开发 频道

C#中对DatagridView的部分常用操作

 14、自定义选择模式

 Set the Selection Mode of the Windows Forms DataGridView Control

 Sample:

 this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

 this.dataGridView1.MultiSelect = false;

 15、自定义设定光标进入单元格是否编辑模式(编辑模式)

 Specify the Edit Mode for the Windows Forms DataGridView Control

 this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

 16、新行指定默认值

 Specify Default Values for New Rows in the Windows Forms DataGridView Control

 Sample:

 private void dataGridView1_DefaultValuesNeeded

 (object sender, System.Windows.Forms.DataGridViewRowEventArgs e)

 {

 e.Row.Cells["Region"].Value = "WA";

 e.Row.Cells["City"].Value = "Redmond";

 e.Row.Cells["PostalCode"].Value = "98052-6399";

 e.Row.Cells["Region"].Value = "NA";

 e.Row.Cells["Country"].Value = "USA";

 e.Row.Cells["CustomerID"].Value = NewCustomerId();

 }

 17、数据验证

 Validate Data in the Windows Forms DataGridView Control

 Samples:

 private void dataGridView1_CellValidating(object sender,

 DataGridViewCellValidatingEventArgs e)

 {

 // Validate the CompanyName entry by disallowing empty strings.

 if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")

 {

 if (e.FormattedValue.ToString() == String.Empty)

 {

 dataGridView1.Rows[e.RowIndex].ErrorText =

 "Company Name must not be empty";

 e.Cancel = true;

 }}}

 18、数据提交到dataset中

 DataSet ds = new DataSet("MyDataSet");

 ds.Tables[biaom.Trim()].Rows.Clear();

 try

 {

 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)

 {

 DataTable dt = ds.Tables[biaom.Trim()];

 DataRow myrow = ds.Tables[biaom.Trim()].NewRow();

 for (int j = 0; j < dataGridView1.Columns.Count; j++)

 {

 myrow[j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value);

 }

 ds.Tables[biaom.Trim()].Rows.Add(myrow);

 }

 }

 catch (Exception)

 {

 MessageBox.Show("输入类型错误!");

 return;

 }

查看原文地址

0
相关文章