chairmanPC
Active member
- Joined
- Apr 19, 2021
- Messages
- 38
- Programming Experience
- 10+
I am trying to get my program in C# to copy and paste a selected row from one DataGridView to another DataGridView. Column 0 is the checkbox cell. The selected rows will be copied into the second DGV. But when I was trying to make this happen, I get NullReferenceException in this line: if ((bool)item.Cells[0].Value == true)
Here is what I did:
Here is my code to browse for file: `
The data in the DGV's come from an excel file. How can I fix this problem?
Here is what I did:
C#:
private void btnAdd_Click(object sender, EventArgs e)
{
selectedDGV.Rows.Clear();
foreach (DataGridViewRow item in allData.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = selectedDGV.Rows.Add();
selectedDGV.Rows[n].Cells[0].Value = item.Cells[3].Value.ToString();
selectedDGV.Rows[n].Cells[1].Value = item.Cells[4].Value.ToString();
selectedDGV.Rows[n].Cells[2].Value = item.Cells[5].Value.ToString();
selectedDGV.Rows[n].Cells[3].Value = item.Cells[6].Value.ToString();
selectedDGV.Rows[n].Cells[4].Value = item.Cells[7].Value.ToString();
selectedDGV.Rows[n].Cells[5].Value = item.Cells[8].Value.ToString();
}
}
}
Here is my code to browse for file: `
C#:
private void button2_Click(object sender, EventArgs e) { try { //updateDataBtn.Enabled = true; selectedDGV.Rows.Clear(); importExcelToDataGridViewApp = new Microsoft.Office.Interop.Excel.Application();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Browse for Excel File";
ofd.Filter = "Excel and CSV Files|*.xlsx;*.csv";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
importExcelToDataGridViewWorkbook = importExcelToDataGridViewApp.Workbooks.Open(ofd.FileName);
importExcelToDataGridViewWorksheet = importExcelToDataGridViewWorkbook.ActiveSheet;
importExcelToDataGridViewRange = importExcelToDataGridViewWorksheet.UsedRange;
for (int rowIndex = 2; rowIndex <= importExcelToDataGridViewRange.Rows.Count; rowIndex++)
{
allData.Rows.Add(null,importExcelToDataGridViewWorksheet.Cells[rowIndex, 1].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 2].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 3].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 6].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 7].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 8].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 9].Value,
importExcelToDataGridViewWorksheet.Cells[rowIndex, 10].Value,
null);
}
}
}catch(Exception eee)
{
ErrorForm error= new ErrorForm();
error.ShowDialog();
error.label3.Text = eee.Message;
}
}
The data in the DGV's come from an excel file. How can I fix this problem?
Last edited by a moderator: