I am trying to copy multiple excel rows to my datagridview, to then be send to my DB. I copy the excel rows using Ctrl + C then i try pasting them using a button click event in the program, but i get an error:
My code as follows :
private void btnPaste_Click(object sender, EventArgs e)
{
try
{
dgvPM.Focus();
dgvPM.CurrentCell = dgvPM[1,1];
string s = Clipboard.GetText();
string[] lines = s.Replace("\n", "").Split('\r');
string[] fields;
int row = 0;
int column = 0;
foreach (string l in lines)
{
fields = l.Split('\t');
foreach (string f in fields)
dgvPM[column++, row].Value = f;
row++;
column = 0;
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I don't know how else i could go about achieving this task. Any help would be appreciated !
UPDATE :
this is how my datagridview looks :
Sample of excel data that I'm pasting :