internal static void CopyData(this DataGridView dataGridView) //internal 内部,对象指定是当前的DataGridView容器上的数据)
{
var a = new ContextMenuStrip();
// 绑定快捷键Ctrl+C
var a_copy = new ToolStripMenuItem { Text = "复制", ShortcutKeys = Keys.C | Keys.Control };
a.Items.Add(a_copy);
//将复制内容粘贴到系统剪切板上面
a_copy.Click += (sender, e) =>
{
//判断容器是否查到数据
if (dataGridView.SelectedRows == null || dataGridView.SelectedRows.Count == 0) return;
//将容器查到的数据添加到剪切板上面去
var objectData = dataGridView.GetClipboardContent();
if (objectData != null) Clipboard.SetDataObject(objectData);
};
dataGridView.CellMouseDown += (sender, e) =>
{
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.Button != MouseButtons.Right) return;
dataGridView.ClearSelection();
dataGridView.Rows[e.RowIndex].Selected = true;
var cell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
var location = dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
a.Show(dataGridView,location.X + e.X , location.Y + e.Y);
};
}
#region 查询SQL参数化
public static SqlDataAdapter CreateCustomerAdapter(SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();
//查询SQL参数化
SqlCommand command = new SqlCommand("SELECT * FROM Customers " + "WHERE Country = @Country AND City = @City", connection);
command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);
command.Parameters.Add("@City", SqlDbType.NVarChar, 15);
adapter.SelectCommand = command;
//插入SQL参数化
command = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (@CustomerID, @CompanyName)", connection);
command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
adapter.InsertCommand = command;
//修改SQL参数化
command = new SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " + "WHERE CustomerID = @oldCustomerID", connection);
command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
SqlParameter parameter = command.Parameters.Add("@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.UpdateCommand = command;
//删除SQL参数化
command = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);
parameter = command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
return adapter;
}
#endregion
内容简记