Hello everyone!
This is the first time to use clipboard to copy data from Excel and paste it into a gridview.
I wrote code like this:
private void gridControlInsert_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 22)
{
PasteData(Clipboard.GetText());
}
}
private void PasteData(string pClipboard)
{
List<List<string>> table = new List<List<string>>();
string importText = pClipboard;
importText = importText.Replace("\n", "");
string[] lines = importText.Split('\r');
for (int x = 0; x < lines.Length; x++)
{
if (string.IsNullOrEmpty(lines[x]))
{
break;
}
List<string> cellsList = new List<string>();
string[] cells = lines[x].Split('\t');
cellsList.AddRange(cells);
table.Add(cellsList);
}
try
{
gridControlInsert.BeginUpdate();
DataView dataView = (DataView)gridViewInsertMas.DataSource;
for (int x = 0; x < table.Count; x++)
{
DataRow row = dataView.Table.NewRow();
for (int y = 0; y < table[x].Count; y++)
{
row[y] = table[x][y];
}
dataView.Table.Rows.Add(row);
}
gridControlInsertMas.DataSource = dataView;
}
My idea is simple:
1. get text from clipboard
2. create a datatable
3. parse the datatable and copy cell by cell into the dataview
My problem comes from the fact that every time when I copy data from Excel, for exemple like this:
999 aaa
888 bbb
It pastes the data into gridview I want but shows
999 aaa(this is a cell) aaa
888 bbb
Then I add a new default row in the gridview, it shows like this:
999 aaa( this is a cell)
999 aaa (2 cells, exactly the same thing in Excel)
888 bbb (2 cells, exactly the same thing in Excel)
I just can't find out where is the problem. I checked the dataView, it seems it is good. I even add MessageBox to see what is in the first cell of dataView, it shows well "999"...
Could anyone help me? Many thanks in advance!!!