Copy data table each row and editing each row - c#

I need to copy each row in a data table with its child row, editing each row in C#.
Please check my code.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[13] { new DataColumn("FIX1"), new DataColumn("FIX2"), new DataColumn("SEQNO")
,new DataColumn("FIX3"),new DataColumn("TRANSACTIONCODE"),new DataColumn("FIX4"),
new DataColumn("CreditAccNo"),new DataColumn("CreditBRNO"),new DataColumn("CreditDate"),
new DataColumn("1LinkCode"),new DataColumn("Debit/creditResonding"),new DataColumn("InstruementNo1"),
new DataColumn("InstruementNo2")});
da.Fill(ds);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
row["FIX1"] = "0";
row["FIX2"] = "0";
row["SEQNO"] = "1";
row["FIX3"] = "0";
row["TRANSACTIONCODE"] = "ZNBPDR";
row["FIX4"] = "0";
row["CreditAccNo"] = "2010100002";
row["CreditBRNO"] = "2";
row["CreditDate"] = DateTime.Now.ToString("dd/MM/yyyy");
row["1LinkCode"] = "71";
row["Debit/creditResonding"] = "2";
row["InstruementNo1"] = "130row2";
row["InstruementNo2"] = "130row2";
txt += row[column.ColumnName].ToString() + "|";
}
//Add new line.
txt += "\r \n";
txt = "";
}

Related

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.

Losing data and gridview C#

I have a program by VC2008 that send dataTable I sended it using the constractor I solve it help at losing data entered in dataview C# - to datagridview in another Form it work fine but I want to send only the new row I tried to copy using ImportRrow it to another datatable but it gives Form2 Blank.
and I send the data as datatable by method as following:
public DataTable showout2()
{
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
DataColumn dc4 = new DataColumn("المالك");
DataColumn dc5 = new DataColumn("قيمة");
DataColumn dc6 = new DataColumn("نوع العملة");
DataColumn dc7 = new DataColumn("الدائن");
DataColumn dc8= new DataColumn("المدين");
DataColumn dc9= new DataColumn("تاريخ");
DataColumn dc10 = new DataColumn("تفاصيل");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
dtab.Columns.Add(dc4);
dtab.Columns.Add(dc5);
dtab.Columns.Add(dc6);
dtab.Columns.Add(dc7);
dtab.Columns.Add(dc8);
dtab.Columns.Add(dc9);
dtab.Columns.Add(dc10);
DateTime date = new DateTime();
date = DateTime.Now;
// Create an array for the values.
object[] newRow = new object[10];
Set the values of the array.
string s = numb.Text;
newRow[0] = numb.Text;
newRow[1] = Account_numb.Text;
newRow[2] = Account_nam.Text;
newRow[3] = owner.Text;
newRow[4] = curency.Text;
newRow[5] = comboBox1.Text;
newRow[6] = Depet.Text;
newRow[7] = cridet.Text;
newRow[8] = date.ToString();
newRow[9] = note.Text;
declare DataRow and adding it to DataTable
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
I transfer the data from Form as following
cashagree fm = cashagree(shouwout2());
I copy the datarow in constractor take datatable as prameter as following:
public Cashagree(DataTable d2)
{
dt.ImportRow(d2.Rows[0]);
}
here I assign the datasource and mange the secound datagridview
private void Cashagree_Load_1(object sender, EventArgs e)
{
try
{
for (int i = 0; i != dt.Rows.Count; i++){
label1.Text= dt.Rows[i].ToString();
if (string.IsNullOrEmpty(dt.Rows[i].ToString()))
{
MessageBox.Show("This is empty");
}
}
dataGridView.DataSource = dt;
dataGridView.Columns[3].Visible = false;
dataGridView.Columns[4].Visible = false;
dataGridView.Columns[5].Visible = false;
dataGridView.Columns[6].Visible = false;
dataGridView.Columns[7].Visible = false;
}
catch (Exception w) { MessageBox.Show("Error" + w.StackTrace); }
}
thank you for helping

Set Focus on DataGridViewCombobox while pressing arrow key up and down

I have a datagridview in which there are three columns .actually this is a dataprocessing application thats why i want use of keyboard(minimal use of mouse)
the code is as follows
[code languge="csharp"]
private void Form2_Load(object sender, EventArgs e)
{
DataTable odt = new DataTable();
DataColumn odc = new DataColumn();
DataColumn odcSec = new DataColumn();
DataColumn odcThird = new DataColumn();
DataColumn odcForth = new DataColumn();
odc.ColumnName = "Class";
odt.Columns.Add(odc);
odcSec.ColumnName = "Subject Name";
odt.Columns.Add(odcSec);
odcThird.ColumnName = "Grade";
odt.Columns.Add(odcThird);
odcForth.ColumnName = "GradeCollection";
odt.Columns.Add(odcForth);
DataRow odr = odt.NewRow();
odr["Class"] = "FYBA";
odr["Subject Name"] = "Hindi";
odr["Grade"] = "A";
odr["GradeCollection"] = "A,B,C,D,E";
odt.Rows.Add(odr);
DataRow odrFirst = odt.NewRow();
odrFirst["Class"] = "SYBA";
odrFirst["Subject Name"] = "English";
odrFirst["Grade"] = "B";
odrFirst["GradeCollection"] = "A,B,C,D,E";
odt.Rows.Add(odrFirst);
DataRow odrSecond = odt.NewRow();
odrSecond["Class"] = "SYBA";
odrSecond["Subject Name"] = "English";
odrSecond["Grade"] = "C";
odrSecond["GradeCollection"] = "A,B,C,D,E";
odt.Rows.Add(odrSecond);
DataRow odrThird = odt.NewRow();
odrThird["Class"] = "TYBA";
odrThird["Subject Name"] = "Marathi";
odrThird["Grade"] = "D";
odrThird["GradeCollection"] = "A,B,C,D,E";
odt.Rows.Add(odrThird);
DataRow odrForth = odt.NewRow();
odrForth["Class"] = "FYBA";
odrForth["Subject Name"] = "Telagu";
odrForth["Grade"] = "E";
odrForth["GradeCollection"] = "A,B,C,D,E";
odt.Rows.Add(odrForth);
if (odt != null && odt.Rows.Count > 0)
{
DataGridViewTextBoxColumn txtClass = new DataGridViewTextBoxColumn();
txtClass.HeaderText = "Class";
txtClass.MaxInputLength = 20;
txtClass.Width = 70;
txtClass.Name = "Class";
kryptonDataGridView1.Columns.Add(txtClass);
DataGridViewTextBoxColumn txtSubjectName = new DataGridViewTextBoxColumn();
txtSubjectName.HeaderText = "SubjectName";
txtSubjectName.MaxInputLength = 20;
txtSubjectName.Width = 70;
txtSubjectName.Name = "SubjectName";
kryptonDataGridView1.Columns.Add(txtSubjectName);
DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.HeaderText = "Grade";
comboboxColumn.DropDownWidth = 160;
comboboxColumn.Width = 90;
comboboxColumn.MaxDropDownItems = 3;
comboboxColumn.FlatStyle = FlatStyle.Flat;
kryptonDataGridView1.TabStop = true;
kryptonDataGridView1.Focus();
kryptonDataGridView1.Columns.Insert(2, comboboxColumn);
for (int i = 0; i < odt.Rows.Count; ++i)
{
string[] row1 = new string[] { odt.Rows[i]["Class"].ToString(), odt.Rows[i]["Subject Name"].ToString() };
kryptonDataGridView1.Rows.Add(row1);
string sItemNames = odt.Rows[i]["GradeCollection"].ToString();
char[] charArray = new char[] { ',' };
string[] sItemNameArray = sItemNames.Split(charArray, StringSplitOptions.RemoveEmptyEntries);
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
dt.Columns.Add(dc1);
DataRow odrinner = dt.NewRow();
odrinner["Name"] = "--Select--";
dt.Rows.Add(odrinner);
foreach (string item in sItemNameArray)
{
dt.Rows.Add(item);
}
comboboxColumn.DataSource = dt;
comboboxColumn.DisplayMember = "Name";
if (!string.IsNullOrEmpty(odt.Rows[i]["Grade"].ToString()))
{
kryptonDataGridView1.Rows[i].Cells[2].Value = odt.Rows[i]["Grade"].ToString();
}
else
{
comboboxColumn.DefaultCellStyle.NullValue = "--Select--";
}
}
}
}
[/code]
Now i want to use arrow key as well as enter key for combobox selection but when i press arrow keys then the focus goes to next row combobox column ,it is not selected that particular combo box.In the same when i use enter key then the focus goes to next column.I want when i hit enter key or arrow key then it select combobox(means focus shuld be on combobox) so that i can select items from that combo box without space hit.
You can use this code:
private void kryptonDataGridView1_CellEnter(object sender,
DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 2)
{
kryptonDataGridView1.BeginEdit(true);
}
}

Data Table Not Binding to Grid View

I am creating a data table and trying to bind it wit a grid view.
Code:
DataTable timeTable = new DataTable();
DataColumn colSubject = new DataColumn("Subject Name");
DataColumn colClass = new DataColumn("Class");
DataColumn colTeacher = new DataColumn("Lecturer");
DataColumn colStartTime = new DataColumn("Start");
DataColumn colEndTime = new DataColumn("End");
colSubject.DataType = System.Type.GetType("System.String");
colClass.DataType = System.Type.GetType("System.String");
colTeacher.DataType = System.Type.GetType("System.String");
colStartTime.DataType = System.Type.GetType("System.String");
colEndTime.DataType = System.Type.GetType("System.String");
timeTable.Columns.Add(colSubject);
timeTable.Columns.Add(colClass);
timeTable.Columns.Add(colTeacher);
timeTable.Columns.Add(colStartTime);
timeTable.Columns.Add(colEndTime);
int numOfRows = 0;
SqlDataReader read = null;
try
{
conn.Open();
read = getTimetable.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
if (numOfRows < 3)
{
DataRow row = timeTable.NewRow();
row[colSubject] = read["subject_name"].ToString();
row[colClass] = read["resource_name_number"].ToString();
row[colTeacher] = read["userDetail_name"].ToString();
row[colStartTime] = read["timeSlot_startTime"].ToString();
row[colEndTime] = read["timeSlot_endTime"].ToString();
timeTable.Rows.Add(row);
numOfRows++;
}
}
gridTimeTable.DataSource = timeTable;
gridTimeTable.DataBind();
}
}
Now The Data table is Created Fine and all cause I used a breakpoint to see whether it was being created the thing is it is not populating the grid view. any ideas?
Thanks :)

How to get selected columns from a datatable

I have a datatable with 10 columns, but User can select the columns to be displayed so I need to create a generic code to display only the selected columns.
Current code:
string[] selectedColumns = new[] { };
DataTable columns = new DataView(table).ToTable(false, selectedColumns);
You could simply hide the columns in the datagridview (supposing you're using one)
dataGridView1.Columns["ColName"].Visible = False;
for every column that are not in selectedColumns
But if you really need to filter the dataset, I remember that you can do something like:
mydatatable.Columns.Remove("ColName");
in your datatable... or in a copy.
If you are going to show the columns in a datagridview, my option will be setting the ColumnMapping property of the datatable column like this
mydatatable.Columns["Colname"].ColumnMapping = MappingType.Hidden;
Unfortunatly I'm not at home now, so I can't test it, but as you can see, there are many options.
EDIT: In response to your request, you can deal with non selected columns like this:
for(int i = 0;i<dt.Columns.Count;i++)
{
if(!selectedColumns.Contains(dt.Columns[i].ColumnName))
{
dt.Columns[i].ColumnMapping = MappingType.Hidden;
}
}
public static void Main(string[] args)
{
DataTable act = new DataTable();
act.Columns.Add(new DataColumn("id", typeof(System.Int32)));
act.Columns.Add(new DataColumn("name"));
act.Columns.Add(new DataColumn("email"));
act.Columns.Add(new DataColumn("phone"));
DataRow dr = act.NewRow();
dr["id"] = 101;
dr["name"] = "Rama";
dr["email"] = "rama#mail.com";
dr["phone"] = "0000000001";
act.Rows.Add(dr);
dr = act.NewRow();
dr["id"] = 102;
dr["name"] = "Talla";
dr["email"] = "talla#mail.com";
dr["phone"] = "0000000002";
act.Rows.Add(dr);
dr = act.NewRow();
dr["id"] = 103;
dr["name"] = "Robert";
dr["email"] = "robert#mail.com";
dr["phone"] = "0000000003";
act.Rows.Add(dr);
dr = act.NewRow();
dr["id"] = 104;
dr["name"] = "Kevin";
dr["email"] = "kevin#mail.com";
dr["phone"] = "0000000004";
act.Rows.Add(dr);
dr = act.NewRow();
dr["id"] = 106;
dr["name"] = "TomChen";
dr["email"] = "tomchen#mail.com";
dr["phone"] = "0000000005";
act.Rows.Add(dr);
var lselColumns = new[] {"id", "name"};
var dt = act.DefaultView.ToTable(true, lselColumns);
foreach (DataRow drow in dt.Rows)
{
string drowData = string.Empty;
foreach (DataColumn r in drow.Table.Columns)
{
drowData += (drowData == string.Empty) ? drow[r] : "|" + drow[r];
}
Console.WriteLine(drowData);
}
Console.ReadLine();
}

Categories

Resources