How do I get my data to show in correct DataGridView column?
I am trying to populate my DataGridView with custom columns imported from Excel. This should be easy but for the life of me, I am stuck in a brainlock. I should be able to select the specific columns (works), send the column headers to my excel class to parse the data from that column (works), send the parsed data to a List (works) and then import the data to the datagridview by setting my DataSource as my List (I am creating the column header text, but the code is creating a column called Value and adding my data to it). Here is my code that is creating the problem:
private void btnCreateTable_Click(object sender, EventArgs e)
{
List<StringValue>[] listArr = new List<StringValue>[columnCount];
ExcelClass getData = new ExcelClass();
tabControl1.SelectedTab = tabDataTable;
dgv.Visible = true;
DataGridViewTextBoxColumn t = new DataGridViewTextBoxColumn();
//dgvSelectedHeaders.Columns[i].Name = selectedHeaders[i];
for (int i = 0; i < columnCo开发者_运维知识库unt; i++)
{
//dgv[i].DataSource = getData.GetDataFromExcel(headersArr[i], path);
listArr[i] = getData.GetDataFromExcel(selectedHeaders[i], path);
t.Name = selectedHeaders[i];
t.HeaderText = selectedHeaders[i];
dgv.Columns.Add(t);
dgv.DataMember = "String";
dgv.DataSource = listArr[i];
for (int j = 0; j < getData.RowCount; j++)
{
dgv.Rows.Add();
for (int k = 0; k < getData.RowCount; k++)
{
dgv[k, j].Value = listArr[j][k].ToString();
}
}
}
If I select more than one column, it shows the first one but I get an error after the first one at row dgv.Columns.Add(t); ... InvalidOperationException, provided column already belongs to the DataGridView control... I know these are two questions, but I think they are tied together somehow.
Thanks in advance, and if you need more code, let me know.
I think you need to create a new DataGridViewColoumn for each column
for (int i = 0; i < columnCount; i++)
{
DataGridViewTextBoxColumn t = new DataGridViewTextBoxColumn();
// ...
dgv.Columns.Add(t);
}
rather than reusing it.
精彩评论