C#数据库工具开发(九)

问题(07/20)

1. 如何实现DataGridView更改Cell值实时同步(像TextBox的效果)?

具体实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private void dataXML_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType().Equals(typeof(DataGridViewComboBoxEditingControl)))//cell为类ComboBox时
{
e.CellStyle.BackColor = Color.FromName("window");
DataGridViewComboBoxEditingControl editingControl = e.Control as DataGridViewComboBoxEditingControl;
editingControl.SelectedIndexChanged += new EventHandler(EditingTB_TypeChanged);
}
else if (e.Control.GetType().Equals(typeof(DataGridViewTextBoxEditingControl)))//cell为类TextBox时
{
e.CellStyle.BackColor = Color.FromName("window");
DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
editingControl.TextChanged += new EventHandler(EditingTB_LengthChanged);
}

}

private void EditingTB_TypeChanged(object sender,EventArgs e)
{

//添加操作
}

private void EditingTB_LengthChanged(object sender,EventArgs e)
{
//添加操作
}

参考:DataGridView的单元格内容即时更新方法

注意点:要用dataGridView1.CurrentCell.EditedFormattedValue而不是dataGridView1.CurrentCell.Value

2. string删除空格

三种方式:
​ string trim = Regex.Replace( text, @”\s”, “” );

1
2
3
4
5
6
7
string trim = text.Replace( " ", "" );  
trim = trim.Replace( "\r", "" );
trim = trim.Replace( "\n", "" );
trim = trim.Replace( "\t", "" );

string text = " My test\nstring\r\n is\t quite long ";
string trim = text.Trim();

3. 获取系统时间

DateTime.Now.ToString("f");//不显示秒

参考:C#获取当前系统时间

4. 导出文件不能立即在目标目录显示文件

解决方法:将包含savefiledialog的窗体显示从showdialog改为show

5. 如何实现DataGridViewTextBox自动把小写转化为大写?

同样用到EditingControlShowing这个事件,另外在DataGridViewTextBox中只需要设置某一列的CharacterCasing为Upper就行。

具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
DataGridView dgv = (DataGridView)sender;
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl editingControl = (DataGridViewTextBoxEditingControl)e.Control;
if (dgv.CurrentCell.OwningColumn.Name == "fieldName")
{
editingControl.CharacterCasing = CharacterCasing.Upper;
}
else
{
editingControl.CharacterCasing = CharacterCasing.Normal;
}
}