@Farshad Valizade, Welcome to Microsoft Q&A, you could try the following code to copy data from excel to datagirdview by using a progressbar to show the progress.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
//backgroundWorker1.WorkerSupportsCancellation = true;
}
List<string> list = new List<string>();
private void ReadFromClipboard(DataGridView dg)
{
if (Clipboard.GetText() != string.Empty)
{
string s = Clipboard.GetText();
string[] lines = s.Replace("\n", "").Split('\r');
list = lines.ToList();
}
//step 2 : fill empty cell in dgv
//for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count - 1; rowIndex++)
//{
// //fill Row Column Number
// dataGridView1.Rows[rowIndex].Cells[0].Value = rowIndex;
// for (int cellIndex = 2; cellIndex < dataGridView1.Rows[rowIndex].Cells.Count; cellIndex++)
// {
// if (String.IsNullOrEmpty(dataGridView1.Rows[rowIndex].Cells[cellIndex].Value.ToString()))
// dataGridView1.Rows[rowIndex].Cells[cellIndex].Value = "*";
// }
//}
}
private void button1_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("Name", "Name");
dataGridView1.Columns.Add("Age", "Age");
dataGridView1.Columns.Add("Id", "Id");
ReadFromClipboard(dataGridView1);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//ReadFromClipboard(dataGridView1);
//for (int i = 0; i < 100; i++)
//{
// Thread.Sleep(1000);
// backgroundWorker1.ReportProgress(i);
//}
string[] fields;
int row = 0;
int col = 0;
foreach (string item in list)
{
dataGridView1.Invoke(new Action(delegate ()
{
dataGridView1.Rows.Add();
}));
fields = item.Split('\t');
foreach (string f in fields)
{
dataGridView1[col, row].Value = f;
col++;
}
row++;
col = 0;
int percentage = (row) * 100 / list.Count;
backgroundWorker1.ReportProgress(percentage);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
}
First : I am confuesd that where should I put my Reading From Clipboard Code?
It is hard to place your ReadFromClipboard method to use the progressbar. I split it into two parts. First part is get the list string from the Clipboard. And second part is used to add rows and add data to the row.
Second : Is there a way to simultaneously add a record to the datagridview when it is read from the clipboard.
It is impossible for you to them simultaneously because you get the data from the Clipboard just one time.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.