write Data to DataRow in DataTable with C# - c#

I have a DataTables with Emails. Over the LDAP I have the Userdata. Now Id like to Increase the DataTable depending upon the EmailAdress.
myDataTable.Columns.Add(new DataColumn("LDAP_Data"));
foreach(DataRow row in modiTable.Rows)
{
string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));
//how to insert to myDataTable > LDAP_Data
}
how can I insert the new Data from LDAP to the new Column?
Thanks

If you add a row to a DataTable you have to add a row which columns match you table. This is why you get back a row if you call DataTable.Add().
Here an example how to add new rows:
static void Main(string[] args)
{
DataTable dt = new DataTable(); // Create a example-DataTable
dt.Columns.Add(new DataColumn() { ColumnName = "Name", DataType = typeof(string) }); // Add some columns
dt.Columns.Add(new DataColumn() { ColumnName = "Id", DataType = typeof(int) });
// Let's fill the table with some rows
for (int i = 0; i < 20; i++) // Add 20 Rows
{
DataRow row = dt.Rows.Add(); // Generate a row
row["Id"] = i; // Fill in some data to the row. We can access the columns which we added.
row["Name"] = i.ToString();
}
// Let's see what we got.
for (int i = 0; i < dt.Columns.Count; i++) // Loop through all columns
{
Console.Write(dt.Columns[i].ColumnName + ";"); // Write the ColunName to the console with a ';' a seperator.
}
Console.WriteLine();
foreach (DataRow r in dt.Rows) // Generic looping through DataTable
{
for (int i = 0; i < dt.Columns.Count; i++) // Loop through all columns
{
Console.Write(r[i] + ";");
}
Console.WriteLine();
}
}

You can do it by using the NewRow method:
foreach(DataRow row in modiTable.Rows)
{
string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));
DataRow row = modiTable.NewRow();
row["EMAIL"] = myLDAPData;
//You might want to specify other values as well
}
Or you can use the Add() method, as suggested in kara's answer.

myDataTable.Columns.Add(new DataColumn("LDAP_Data"));
foreach(DataRow row in modiTable.Rows)
{
string myLDAPData = DoLDAPAction(row.Field<string>("EMAIL"));
var row = myDataTable.NewRow()
row["LDAP_Data"] = YOUR_DATA;
myDataTable.Rows.Add(row);
}

Related

How to read textfile to datatable in c#

Below is my class code
public class TextReaderClass
{
public DataTable ReadTextFile(string filepath)
{
DataTable dtTextFile = new DataTable();
dtTextFile.Columns.Add("Emp_Id");
dtTextFile.Columns.Add("Emp_FirstName");
dtTextFile.Columns.Add("Emp_LastName");
dtTextFile.Columns.Add("Emp_Designation");
dtTextFile.Columns.Add("Emp_Salary");
dtTextFile.Columns.Add("Emp_JoiningDate");
//CODE to add here reading from text file and filling the data table
string[] readTextfile = System.IO.File.ReadAllLines(#"D:\Rutu\datatest.txt");
//Run a loop here for each record in the text file
foreach (string line in readTextfile)
{
var cols = line.Split(';');
DataRow dtrow = dtTextFile.NewRow();
//Create an object of Data Row
dtTextFile.Rows.Add(dtrow);
//Fill the row data in DataTable
}
return dtTextFile;
}
}
I tried this CODE for reading from text file and filling the data table. Any help will be highly appreciated. Thanks
You can do like that by doing this you you also read and add it to datatable
public DataTable ReadTextFile(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for(int col =0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col+1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach(string line in lines)
{
var cols = line.Split(':');
DataRow dr = tbl.NewRow();
for(int cIndex=0; cIndex < 3; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
try this code.
public DataTable ReadTextFile(string filepath,int numberOfColumns)
{
DataTable dtTextFile = new DataTable();
for(int col =0; col < numberOfColumns; col++)
dtTextFile.Columns.Add(new DataColumn("Column" + (col+1).ToString()));
string[] readTextfile = System.IO.File.ReadAllLines(filepath);
foreach (string line in readTextfile)
{
var cols = line.Split(';');
DataRow dtrow = dtTextFile.NewRow();
for(int cIndex=0; cIndex < 3; cIndex++)
{
dtrow [cIndex] = cols[cIndex];
}
dtTextFile.Rows.Add(dtrow);
}
return dtTextFile;
}
And also get datatable to gridview
dataGridview.DataSource=ReadTextFile(filepath,6);
If you have a formatted text file and MS SQL Server consider using the bulk insert facility:
https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-ver15
An example:
BULK INSERT Sales.Orders FROM 'C:\Rutu\datatest.txt' WITH ( FORMAT='CSV');

Column data from Sql Server not position as match with column in Datatable

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";

Creating DataTable from Text File and splitting

This is going to be my text file (30 lines)
OrderNo:37374
OrderQuantity:250
BarcodeQR:584,25478Klkd28
NormalBarcode:1565484864
.......
.......
.......
This is the code :
public DataTable DTforReport()
{
DataTable dt = new DataTable();
DataColumn col = new DataColumn("test");
col.DataType = System.Type.GetType("System.String");
dt.Columns.Add(col);
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
foreach (var line in lines)
{
var segments = line.Split(';');
foreach (var seg in segments)
{
DataRow dr = dt.NewRow();
dr[0] = seg;
dt.Rows.Add(dr);
}
}
return dt;
}
I want my output like this
OrderNo OrderQuantity BarcodeQR
37374 250 584,25478Klkd28
How can I change my code to achieve this?
You have generated only one column. Change your code like below to see your desired result:
public DataTable DTforReport()
{
DataTable dt = new DataTable();
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
DataRow dr = dt.NewRow();
for (int i = 0; i < lines.Length; i++)
{
DataColumn col = new DataColumn(lines[i].Split(':')[0]);
col.DataType = Type.GetType("System.String");
dt.Columns.Add(col);
var segment = lines[i].Split(':')[1];
dr[i] = segment;
}
dt.Rows.Add(dr);
return dt;
}
I suggest you to modify your method like the following:
public DataTable DTforReport()
{
DataTable testTable = new DataTable("Test");
testTable.Columns.Add("OrderNo");
testTable.Columns.Add("OrderQuantity");
testTable.Columns.Add("BarcodeQR");
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
foreach (var line in lines)
{
DataRow dRow = testTable.NewRow();
var segments = line.Split(';');
for (int i = 0; i < segments.Length; i++)
{
var colValues = segments[i].Split(':');
dRow[i] = colValues[1];
}
testTable.Rows.Add(dRow);
}
return testTable;
}
Few suggestions for improvement:
I have given static column names, if you want to add more or they may change in future means you can create dynamic columns in the datatable.
If you have doubts in the input values, make use of proper validation
Validations in the sense, make sure about the splitted values before accessing them through index otherwise they may ends up with IndexOutOfRangeException
DataTable dt = new DataTable();
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
var firstLine = lines.First();
var columns = firstLine.Split(';');
for (var icount = 0; icount < columns.Count(); icount++)
{
var colName = columns[icount].Contains(":") ? columns[icount].Split(':')[0] : "Column" + icount;
var dataCol = new DataColumn(colName);
dataCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(dataCol);
}
foreach (var line in lines)
{
DataRow dr = dt.NewRow();
var segments = line.Split(';');
for (var icount = 0; icount < segments.Count(); icount++)
{
var colVal = segments[icount].Contains(":") ? segments[icount].Split(':')[1] : "";
dr[icount] = colVal;
}
dt.Rows.Add(dr);
}
*Number of column must be same in each row.

How to programmatically add rows to DataGrid in C#?

So as the title states, I'm trying to add rows to a DataGrid programmatically using C# but I can't seem to make it work. This is what I have so far.
// I have a DataGrid declared as dg in the XAML
foreach (string s in array) {
int index = 0;
DataGridRow dgRow = new DataGridRow();
foreach (DataGridColumn dgColumn in columns)
{
// Trying to add Text to dgRow here but IDK how
index++;
}
}
I've been googling around and the closest I got to adding anything was to use {column = value} but it just throws me an error. Really out of ideas now though :\
Here's you can do it better way by binding a source to datagridview
// Creating DataSource here as datatable having two columns
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name");
// Adding the rows in datatable
for (int iCount = 1; iCount < 6; iCount++)
{
var row = dt.NewRow();
row["ID"] = iCount;
row["Name"] = "Name " + iCount;
dt.Rows.AddRow(row);
}
DataGridView dgv = new DataGridView();
// Set AutoGenerateColumns true to generate columns as per datasource.
dgv.AutoGenerateColumns = true;
// Finally bind the datasource to datagridview.
dgv.DataSource = dt;
In Case you are using WPF DataGrid
you can bind it like this way-
dgv.DataContext = employeeData.DefaultView;
and in
XAML
<DataGrid Name="dgv" ItemsSource="{Binding}">
//create datatable and columns,
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Column 1"));
dtable.Columns.Add(new DataColumn("Column 2"));
//simple way create object for rowvalues here i have given only 2 add as per your requirement
object[] RowValues = { "", "" };
//assign values into row object
RowValues[0] = "your value 1";
RowValues[1] = "your value 2";
//create new data row
DataRow dRow;
dRow = dtable.Rows.Add(RowValues);
dtable.AcceptChanges();
//now bind datatable to gridview...
gridview.datasource=dbtable;
gridview.databind();
Regards
did you try?:
int n=5; // number of rows you want to add
dataGridView1.Rows.Add(n);
// you can add (names of the rows) if you have them in your array
//for(int i=0; i<n; i++)
//dataGridView1[0, i].Value = array[i];

Getting a dataset from an unbound datagridview

I have a datagridview that is not bound directly do a datasource. Instead, I add the data from various methods during runtime. I created a method that accepts a dataSet and outputs it into Excel, but I can't find if there is an in-built way to geta dataSet from a dataGridView.
Thanks.
I updated the code to work. There was a few typos in the previous answer.
DataTable dt = new DataTable();
for (int i = 0; i < dgvPaperAndPlastic.Columns.Count; i++)
{
DataColumn column = new DataColumn(dgvPaperAndPlastic.Columns[i].HeaderText);
dt.Columns.Add(column);
}
int noOfColumns = dgvPaperAndPlastic.Columns.Count;
foreach (DataGridViewRow dr in dgvPaperAndPlastic.Rows)
{
//Create table and insert into cell value.
DataRow dataRow = dt.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dr.Cells[i].Value.ToString();
}
}

Categories

Resources