The data in InvtID already match with "3" column once I import an Excel file, but the problem is as shown in the photo why the data column (InvtID) filled in datatable after the last row data? How am I able to fix the position to match with "3" column. I already position the InvtID column at 0. Is there any single line code to start position the row at 1?:
public void filldatagridview(ExcelWorksheet workSheet)
{
DataTable dt = new DataTable();
//Create the data column
for (int col = workSheet.Dimension.Start.Column;
col <= workSheet.Dimension.End.Column; col++)
{
dt.Columns.Add(col.ToString());
}
for (int row = 12; row <= 26; row++)
{
DataRow newRow = dt.NewRow(); //Create a row
int i = 0;
for (int col = workSheet.Dimension.Start.Column;
col <= workSheet.Dimension.End.Column; col++)
{
newRow[i++] = workSheet.Cells[row, col].Text;
}
dt.Rows.Add(newRow);
}
dt.Columns.RemoveAt(0); //remove No
dt.Columns.RemoveAt(0); //remove article
//Get BookCode
var barCodes = dt.AsEnumerable().Select(r => r.Field<string>("3"))
.ToArray(); //EAN column
var barCodesstring = string.Format("'{0}'", string.Join("','", barCodes));
SqlCommand cmd = new SqlCommand("SELECT InvtID FROM InventoryCustomer WHERE
Barcode IN (" + barCodesstring + ")", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dt.Columns["InvtID"].SetOrdinal(0);
dataGridView2.DataSource = dt;
conn.Close();
}
This code always adds a new row DataRow newRow = dt.NewRow();
, so your rows are not matched:
for (int row = 12; row <= 26; row++)
{
DataRow newRow = dt.NewRow(); //Create a row
//...
dt.Rows.Add(newRow);
}
But if I understood correctly, you want to set data into specific data cells. Then you should find existing row and set the cell value:
DataRow dr = dt.Rows[yourRowNumber];
dr[3] = "Your New Value";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.