In my project I had the following question:
- I have 2
dataGridView
, wheredataGridView1
would be a list of products (one querySQL
of products). - I would like to know if I can drag this
dataGridView1
and drop thedataGridView2
that would be the purchase that the customer is taking and be able to save this other information as invoice #xxx.
I'm trying with this code and the item is not sent, what will it be?
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public event DragEventHandler DragDrop;
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string connstring = String.Format("Server=localhost;Port=5432;User Id=postgres;Password=123;Database=BDsystem");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
string sql = "SELECT * FROM simple_table";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
conn.Close();
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
throw;
}
}
private void MouseDown(object sender, MouseEventArgs e)
{
var hitTestInfo = dataGridView1.HitTest(e.X, e.Y);
if (hitTestInfo.RowIndex > -1)
{
dataGridView1.DoDragDrop(hitTestInfo.RowIndex,
DragDropEffects.Copy | DragDropEffects.Move);
}
}
private void dataGridView2_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data.GetDataPresent(DataFormats.StringFormat) ? DragDropEffects.Copy : DragDropEffects.None;
}
private void dataGridView2_DragDrop(object sender, DragEventArgs e)
{
string dropData = e.Data.GetData(DataFormats.Text).ToString();
int rowIndex = int.Parse(dropData);
var cells = dataGridView1.Rows[rowIndex].Cells.Cast<DataGridViewCell>()
.Select(c => c.Value).ToArray();
dataGridView2.Rows.Add(cells);
dataGridView1.Rows.RemoveAt(rowIndex);
}
}
}