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

问题(07/19)

1. 如何实现拖拽文件到textbox获取文件路径?

利用textbox两个事件:dragenter和dragdrop
具体实现

1
2
3
4
5
6
7
8
9
10
11
private void filePath_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Link;
}
else
{
e.Effect = DragDropEffects.None;
}
}
1
2
3
4
5
private void filePath_DragDrop(object sender, DragEventArgs e)
{
string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
filePath.Text = path;
}

2. 数据库如何增删改字段?

只考虑SQLServer和Oracle,增加和删除字段可用相同sql语句,修改字段略有不同:

增加:
sql = @"use " + DBName + "; ALTER TABLE " + tableName + " ADD " + fieldName + " " + fieldType + "(" + fieldLength + ");";

删除:
sql = @"use " + DBName + "; ALTER TABLE " + tableName + " DROP COLUMN " + fieldName + ";";

修改:

SQLSerer:sql = @"use " + DBName + "; ALTER TABLE " + tableName + " ALTER COLUMN " + fieldName + " " + fieldType + "(" + fieldLength + ");";

Oracle:sql = @"ALTER TABLE " + tableName + " modify(" + fieldName + " " + fieldType + "(" + fieldLength + "))";

3. 如何导出文件?

使用SaveFileDialog控件

具体实现:

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
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "TXT|*.txt";
saveFileDialog1.Title = "选择导出sql记录的存储路径";
saveFileDialog1.ShowDialog();

// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
StreamWriter sw = new StreamWriter(fs);
foreach(string result in sqlcommands)
{
sw.WriteLine(result);
}

//清空缓冲区
sw.Flush();
//关闭流
sw.Close();

fs.Close();
}

4. 如何给DataGridView增加行号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void dataXML_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();

var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};

var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}