【发布时间】:2015-03-23 00:42:00
【问题描述】:
我想允许用户添加行,但空白行必须在他的第一个位置,让用户输入数据而无需每次向下滚动以插入新行?!
这就是我在 datagridview 中添加行的方式:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;
namespace Parc_Automobile
{
public class SqlHelper
{
private const string ConnectionString =
"Data Source=KIM;Initial Catalog=TestingBlank;Integrated Security=True";
private readonly DataGridView _dgv;
private BindingSource _bindingSource;
private DataTable _dataTable;
private string _selectQueryString;
private SqlConnection _sqlConnection;
private SqlDataAdapter _sqlDataAdapter;
protected SqlHelper(DataGridView dgv)
{
_dgv = dgv;
}
//display a table in datagridview
public void ShowTable(String tableName)
{
_sqlConnection = new SqlConnection(ConnectionString);
_sqlConnection.Open();
_selectQueryString = "SELECT * FROM " + tableName;
_sqlDataAdapter = new SqlDataAdapter(_selectQueryString, _sqlConnection);
var sqlCommandBuilder = new SqlCommandBuilder(_sqlDataAdapter);
_dataTable = new DataTable();
_sqlDataAdapter.Fill(_dataTable);
_bindingSource = new BindingSource {DataSource = _dataTable};
var tempRow = this._dataTable.NewRow();
this._dataTable.Rows.InsertAt(tempRow, 0);
_dgv.DataSource = _bindingSource;
_sqlConnection.Close();
}
//Search In datagridview using input of users
public void SearchTable(String SearchText, String columnNameToSearch, int type)
{
try
{
var filterBuilder = "";
switch (type)
{
case TEXT_COLUMN:
filterBuilder = columnNameToSearch + " LIKE '" + SearchText + "%'";
break;
case NUMERIC_COLUMN:
filterBuilder = columnNameToSearch + " = '" + SearchText + "'";
break;
}
var bs = new BindingSource
{
DataSource = _dgv.DataSource,
Filter = filterBuilder
};
_dgv.DataSource = bs;
}
catch (Exception e)
{
// ignored
}
}
public void DeleteRow()
{
if (_dgv.CurrentRow != null) _dgv.Rows.RemoveAt(_dgv.CurrentRow.Index);
_sqlDataAdapter.Update(_dataTable);
}
public void SaveChanges(Label label)
{
try
{
_sqlDataAdapter.Update(_dataTable);
label.Text = "Changement a été effectué avec succès.";
}
catch (Exception e)
{
MessageBox.Show("" + e);
}
}
}
}
【问题讨论】:
标签: c# winforms c#-4.0 datagridview