Add column to DataTable and move columns to right - c#

I have a DataTable with 2 columns in it. I would like to insert another column to the start, and move those 2 columns to the right by 1.
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
Any ideas how I could do this?
Thanks.

Try this.
DataColumn column = dtCurrentTable.Columns.Add("Column Name", typeof(<<The data type of your column>>));
column.SetOrdinal(0);// to put the column in position 0;

Do Something like this>>
DataTable workTable = new DataTable("Customers");
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
Hope its helpfull.

Related

Can't force DataGridView generate columns

I'm creating both datatable and datagridview on the fly and simply want the grid to generate columns from that table.
// create simple datatable
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
DataGridView dgv = new DataGridView() { AutoGenerateColumns = true };
// None of the below force datagridview to generate columns
dgv.DataSource = dt;
Debug.WriteLine($"Grid columns count: {dgv.Columns.Count}");
dgv.DataSource = new BindingSource(dt, null);
Debug.WriteLine($"Grid columns count: {dgv.Columns.Count}");
Columns count in data grid view is still zero after I set datasource.
What am I doing wrong?
You can create a DataTable and give it some columns then add this DataTable as datagridview columns
DataTable dt = new DataTable();
Once you declared it build a functions such this:
void createDataTable()
{
dt.Columns.Add("column1");
dt.Columns.Add("column2");
yourdatagridview.DataSource = dt;
}
Last call the function in your form cunstructor:
createDataTable();

How to bind data to the columns in C# Windows Forms grid view, which are stored in rows in SQL table

Please refer the images. How to bind the SQL table data which are stored in rows in to data grid view (C# Windows Forms) as columns. Also I have created column[0] as a hard coded column. I need to bind these data which is coming from SQL to column1. Please help me. Thanks in advance . :-)
You can create a method which rotate the DataTable and swap columns and rows this way:
public DataTable Rotate(DataTable table)
{
var output = new DataTable();
int i = 1;
output.Columns.Add(" ");
foreach (DataRow r in table.Rows)
output.Columns.Add((i++).ToString());
foreach (DataColumn c in table.Columns)
{
var list = new List<object>();
list.Add(c.ColumnName);
var x = table.AsEnumerable().Select(r => string.Format("{0}", r[c])).ToArray();
list.AddRange(x);
output.Rows.Add(list.ToArray());
}
return output;
}
Then you can use it to rotate the original table:
to rotated table:
or even with some simple tricks like this:
Here is the code which I used to create the example:
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Date", typeof(DateTime));
dt.Rows.Add(100, "A", DateTime.Now);
dt.Rows.Add(200, "B", DateTime.Now.AddDays(1));
dt.Rows.Add(300, "C", DateTime.Now.AddDays(2));
dt.Rows.Add(400, "D", DateTime.Now.AddDays(3));
this.dataGridView1.DataSource = dt;
this.dataGridView2.DataSource = Rotate(dt);
//To hide column headers and show Id,Name,Date on rows headers, un-comment following codes:
//dataGridView2.ColumnHeadersVisible = false;
//dataGridView2.Columns[0].Visible = false;
//for (int i = 0; i < dataGridView2.Rows.Count; i++)
// dataGridView2.Rows[i].HeaderCell.Value = dataGridView2.Rows[i].Cells[0].Value;

Windows Form DataGridView not getting DataSet

What is wrong with my code?
dataSet = new DataSet();
dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"] };
string site = "mysite";
UInt64 itemId = 44322;
string itemName = "werwer";
decimal listedPrice = 345345;
string currency = "USD";
dataTable.Rows.Add(site, itemId ,itemName, listedPrice, currency);
dataGridView1.DataSource = dataSet.Tables["Items"];
When I run it, it does not enter the row to the GridView, simply adding a blank line
EDIT
I found the problem, it was because I manually created the cells in VS IDE.
How can I still work with the IDE because I want to fix the layout not by code
Try this once..
DataSet dataSet = new DataSet();
DataTable dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"]
dataTable.Rows.Add("mysite",44322,"werwer", 345345,"USD");
dataGridView1.DataSource = dataSet.Tables["Items"]

How to add new DataRow into DataTable?

I have a DataGridView binded to a DataTable (DataTable binded to database). I need to add a DataRow to the DataTable. I'm trying to use the following code:
dataGridViewPersons.BindingContext[table].EndCurrentEdit();
DataRow row = table.NewRow();
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
But it doesn't work, DataGridView has never been added a new row. Please, tell me, how can I fix my code?
Thank you in advance.
You can try with this code - based on Rows.Add method
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Reference: https://learn.microsoft.com/dotnet/api/system.data.datarowcollection.add?view=net-5.0#System_Data_DataRowCollection_Add_System_Data_DataRow_
I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}
//َCreating a new row with the structure of the table:
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
//Giving values to the columns of the row(this row is supposed to have 28 columns):
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
You have to add the row explicitly to the table
table.Rows.Add(row);
If need to copy from another table then need to copy structure first:
DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);
This works for me:
var table = new DataTable();
table.Rows.Add();
try table.Rows.add(row); after your for statement.
GRV.DataSource = Class1.DataTable;
GRV.DataBind();
Class1.GRV.Rows[e.RowIndex].Delete();
GRV.DataSource = Class1.DataTable;
GRV.DataBind();

Assign value to a specific Column in Datatable using c#

I have created a datatable and added many columns to it.
When the datatable is empty, i want to assign a value to a specific column.
Like finding the column name in datatable and assign value to it... Is it possible ? Thanks
dt_FAQ.Columns.Add("FQ_Question_1", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_1", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_2", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_2", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_3", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_3", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_4", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_4", typeof(string));
dt_FAQ.Columns.Add("FQ_Question_5", typeof(string));
dt_FAQ.Columns.Add("FQ_Answer_5", typeof(string));
There is a scenario where i would get only the value that has to be assigned to column "FQ_Answer_1" in the above datatable. In that case, i want to assgn value to that column alone and pass empty string "" to other columns. Possible ?
In case of your existing datatable with data inside, you have to iterate through the datatable rows and set values to each column
foreach(DataRow dr in dt_FAQ.Rows)
{
dr["FQ_Answer_1"] = "your value";
dr["FQ_Question_1"] = string.Empty;
dr["FQ_Question_2"] = string.Empty;
//.... for all the columns
}
To find a particular column you can do:
DataColumn dc = dt.Columns.Cast<DataColumn>().Where(r => r.ColumnName == "yourname").FirstOrDefault();
//Or simpler
DataColumn dc2 = dt.Columns["yourcol"];
EDIT: For new Row:
DataRow dr = dt_FAQ.NewRow();
dr["FQ_Answer_1"] = "some value";
dt_FAQ.Rows.Add(dr);
This will create a new row with "some value" for column FQ_Answer1, all the other remaining columns will have string.Empty as default value.
You can check other columns like:
string test = dt_FAQ.Rows[0]["FQ_Question_1"].ToString();
Here test will contain an empty string.
How about
DataRow dr = mydatatable.NewRow();
dr[0] = 1; // Assuming that first column is int type
dr[0] = "someothervalue"; //Assuming that second column is string type
..
..
..
.. // Repeat for other columns.
mydatatable.AddRow(dr);

Categories