Dynamically add data to column - c#

So i had to make a running balance column based on an existing data table.
I have the formulas and everything.
I would just like to know if it is possible to make another column in that data table and generically add data to it based on the result of the formula,
currently I loop through the table row by row and equate the last column, can I put the result in that same row?
Thanks everyone

DataColumn newColumn = new DataColumn("ColumnName", typeof(System.String)); // I considered the column datatype as string, u can give as u want
newColumn.DefaultValue = "Your Value";
dataTable.Columns.Add(newColumn);
We can add a new column with default value as above..
If you want add some other value means, go for for-loop or foreach..
foreach (DataRow DR in dataTable.Rows)
{
DR["ColumnName"] = "Your Value";
}

Yes, you can add a new column to the data table any time, and once added, can always set the value of the RunningBalance cell (column + row) to the value you calculated.
DataColumn runningBalanceColumn = myDataTable.Columns.Add("RunningBalance", typeof(Int64));
runningBalanceColumn[0] = RUNNING_BALANCE_FOR_FIRST_ROW;
// and so on

Also refer [MSDN][1]
// Create total column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "Price+ Quantity";
// Add columns to DataTable.
...
table.Columns.Add(totalColumn);

Related

How can I send the selected rows of a DataGridView to a Datatable, BUT ignoring the first column?

Hellou to everyone.
I would love the assistance from you guys.
My problem is like this:
I have this datagridview which I fill using datasource (a query to a db table). I only created manually one column which contain a checkbox. When the binding is complete I can click the checkboxes to select the row and I can select multiples rows this way.
I want to put the selected rows into a datatable (so I can read it and do some sql queries with the information on it) BUT when I read the selected rows to put them inside a datatable I need to skip the checkbox column (the first one).
How can I achieve this?
Okay, for future reference, I'm gonna post here how I fixed it.
DataTable dt = new DataTable();
if (dgvPedidos.SelectedRows.Count > 0)
{
foreach (DataGridViewColumn column in dgvPedidos.Columns)
dt.Columns.Add();
int i = 0;
foreach(DataGridViewRow row in dgvPedidos.Rows)
{
if (Convert.ToBoolean(dgvPedidos.Rows[i].Cells["chkPedido"].Value) == true)
{
dt.Rows.Add();
dt.Rows[i][1] = row.Cells[1].Value.ToString();
dt.Rows[i][2] = row.Cells[2].Value.ToString();
dt.Rows[i][3] = row.Cells[3].Value.ToString();
dt.Rows[i][4] = row.Cells[4].Value.ToString();
dt.Rows[i][5] = row.Cells[5].Value.ToString();
dt.Rows[i][6] = row.Cells[6].Value.ToString();
dt.Rows[i][7] = row.Cells[7].Value.ToString();
dt.Rows[i][8] = row.Cells[8].Value.ToString();
dt.Rows[i][9] = row.Cells[9].Value.ToString();
i++;
}
}
dt.Columns.RemoveAt(0);

How to remove time from datetime column in dataset?

I have to export data to excel sheet in asp.net c# application. Now I have wriiten below lines of code
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
row["ExpiryDate"] = Convert.ToDateTime(row["ExpiryDate"]).ToShortDateString();
}
DataSet dsn = new DataSet();
DataTable dtcopy = dt.Clone();
dsn.Tables.Add(dtcopy);
WebUtility.GenrateExcel(ds, "ExpiredDocuments");
I want to first remove time from data set's Expiry date column and then pass
it to the generate Excel function so that time will not appear in Expiry date column in excel... Please help the above code is not working...
I guess, you need look through this:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You should use smth like
Convert.ToDateTime(ds.Tables[0].Rows[i]["ExpiryDate"]).ToString("MM/dd/yyyy")
Or whatever you need.
These are the steps you need to do in order to accomplish what you are asking:
Create a new column of type string
Set the new column's value to ShortDateString of the corresponding "ExpiryDate" column
Remove the "ExpiryDate" column
Move the new string column to the position of the old "ExpiryDate" column
Rename the new column to "ExpiryDate"
Like so:
dt.Columns.Add("ExpiryDateString", typeof(String));
foreach(DataRow row in dt.Rows)
{
row["ExpiryDateString"] = ((DateTime)row["ExpiryDate"]).ToShortDateString();
}
int columnNumber = dt.Columns["ExpiryDate"].Ordinal;
dt.Columns.Remove("ExpiryDate");
dt.Columns["ExpiryDateString"].SetOrdinal(columnNumber);
dt.Columns["ExpiryDateString"].ColumnName = "ExpiryDate";

How to change value in data row with type mismatch?

I have a DataTable that I'm exporting to pdf and there are numeric value like status id that I want to change to strings for example:
dataRow["statusId"] = 1; //dataRow["statusId"] type is int
and I want it to be:
dataRow["statusId"] = "Open file";
How can I do it without coping the entire data table ?
You actually can't do it. The best way is to actually clone the dataTable and then copy each row:
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32); //in the column you actually need.
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
Source: How To Change DataType of a DataColumn in a DataTable?

c# adding row to datatable which has an auto increment column

I've a datatable, with column A, B, C. I've set column A's "is identity" property to true, but I can't add any row to the table now.
The code I'm trying is this:
dsA.dtA row = dsA.dtA.NewdtARow();
row.B = 1;
row.C = 2;
dsA.dtA.Rows.Add(row);
I'm getting NoNullAllowedException, but I don't understand why. Column A is PK as well. If I tried to set row.A = 5 (or any similiar) I'll get an error when I try to update the datatable saying "cannot insert explicit value for identity column in table when identity_insert is set to off"
How can I solve this issue? It's frustrating.
Do this way. Reference link
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 1;
column.AutoIncrementStep = 1;
// Add the column to a new DataTable.
DataTable table = new DataTable("table");
table.Columns.Add(column);
DataRow oRow = table.NewRow();
table.Rows.Add(oRow);
Open the designer of the dataset xsd file and set the AutoIncrement, AutoIncrementSeed and AutoIncrementStep property of the column A in datatable for an existing column.
Try one of the these two:
Set field values:
row.A = null;
row.B = 1;
row.C = 3;
Add row to DataTable:
dtA.Rows.Add(null,1,2);
They are both the same just try any of them and it should get you going. Also remember that whenever you want to make a column auto-increment in DataTable then you have to insert null into it.
The way that I do it is
public void AppendtodtA(int num1, doubledouble1, string string1)
{
object[] RowArray = new object[] {null,(int)num1, (double) doubledouble1, (string) string1}
DataRow CurrentRow = dtA.NewRow();
CurrentRow.ItemArray = RowArray;
dtA.Rows.Add(CurrentRow);
}
use ItemArray property and leave a null in the place of the autoincremented column
AppendtodtA(MyNumber,MyDouble,MyString);
Then just call the method with your variables.

How can I add a new column and data to a datatable that already contains data?

How do I add a new DataColumn to a DataTable object that already contains data?
PseudoCode
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", type(System.Int32));
foreach(DataRow row in dr.Rows)
{
//need to set value to NewColumn column
}
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
Should it not be foreach instead of for!?
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("MyRow", **typeof**(System.Int32));
foreach(DataRow dr in dt.Rows)
{
//need to set value to MyRow column
dr["MyRow"] = 0; // or set it to some other value
}
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
Try this
> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value;

Categories