Assign value to a specific Column in Datatable using c# - 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);

Related

C# GetDataType from String in DataTable

I have a DataTable that is populated with only strings at the moment.
I want to get from the DataTable Columns the DataType and insert the DataType.
DataTable example, all row names can be random.
And I want to have from the example Column "age" as int, and the rest still string.
At the moment the Age is a string, can I try to Parse the whole column? Or would this be a bad solution.
Is there a simple way to do this?
You can not change the data type once the table is loaded. Clone the current DataTable from the original table, find the age column, change data type from string to int then import rows.
Important: The above assumes that, in this case the age column can represent an int on each row, if not you need to perform proper assertion before using ImportRow.
Here is a conceptual example
private static void ChangeColumnType()
{
DataTable table = new DataTable();
table.Columns.Add("Seq", typeof(string));
table.Columns.Add("age", typeof(string));
table.Columns.Add("name", typeof(string));
table.Rows.Add("1", "22", "Smith");
table.Rows.Add("2", "46", "Jones");
DataTable cloned = table.Clone();
bool found = false;
for (int index = 0; index < table.Columns.Count; index++)
{
if (string.Equals(table.Columns[index].ColumnName, "age",
StringComparison.CurrentCultureIgnoreCase))
{
cloned.Columns["age"]!.DataType = typeof(int);
found = true;
}
}
if (!found) return;
foreach (DataRow row in table.Rows)
{
cloned.ImportRow(row);
}
foreach (DataColumn column in cloned.Columns)
{
Console.WriteLine($"{column.ColumnName}\t{column.DataType}");
}
}
Edit: One possible way to avoid issues when age can not be converted to an int.
if (!found) return;
foreach (DataRow row in table.Rows)
{
if (int.TryParse(row.Field<string>("age"), out _))
{
cloned.ImportRow(row);
}
else
{
Console.WriteLine($"Failed: {string.Join(",", row.ItemArray)}");
}
}
Sorry if I do not understand your question but I will try to answer what I think you're asking below:
If you're just trying to determine the data type then I would suggest taking the first value in said column (as you don't need to check them all obviously.) And do a tryparse to determine if it is compatible with int for example.
If you used getType it would likely return a String.
If you're trying to SET the whole column as a data type then you should probably be doing this at the stage you're generating the table via a constructor or programatically as shown in the first example
// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
column.Caption = "ParentItem";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
Full Example from Microsoft

How can I set read only property for Particular 'dr' in DATAROW

I try to shown a particular row as a read only format for ListBox. But when getting value from database I can't able to set the read only property for the particular row.
C#:
DataTable dt = new DataTable();
dt.Columns.Add("SectionId", typeof(string));
dt.Columns.Add("RegionalLanguage1", typeof(string));
foreach(DataTable table in dsPopularPrograms.Tables)
{
foreach(DataRow dr in table.Rows)
{
var IsDisable = dr["IsPrabalamanavai"].ToString();
DataRow newRow = dt.NewRow();
newRow["SectionId"] = dr["SectionId"].ToString();
newRow["RegionalLanguage1"] = dr["RegionalLanguage1"].ToString();
if (IsDisable == "D")
{
//Need to set the row as readonly
}
dt.Rows.Add(newRow);
}
}
In the particular condition I want to set the read only property. I don't know how it is.
Please give some suggestion.

Filtering Items from DataGridview to a DataTable produces Invalid Results

I have the following datagridview.
I need to filter and save rows separately that match Valid and Invalid property of the status column.
It do not have a datasource.So i'm creating a DataTable,filtering it and saving the results.But the filtering is not working as intended and contains results that does not match the expression
DataTable dt = new DataTable();
//Populating Virtual Table
foreach (DataGridViewColumn col in dataGridView4.Columns)
{
dt.Columns.Add(col.Name);
}
foreach (DataGridViewRow row in dataGridView4.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
Now creating a Filtered Table containing results where column named Status equals "Valid"
filtered = dt.Copy();
DataTable filteredResults = new DataTable();
DataTable filteredResults2 = new DataTable();
// filtered.Columns.Remove("Status");
var expression = string.Format("Status LIKE '%{0}%'", "Valid");
if (filtered.Select(expression).Any())
{
filteredResults = filtered.Select(expression).CopyToDataTable();
}
But the filtered data table contains elements which has the Status column value "Invalid".What i'm i doing wrong ? Please advice.
You are using LIKE in your expression. LIKE checks to see if the value contains the specified value. Use = instead.

How to Bind DataTable to DataGridView

I am trying to bind DataTable to DataGridView as below;
DataTable table = new DataTable();
foreach (ConsumerProduct c in ctx.ConsumerProducts)
{
DataRow row = table.NewRow();
row["Id"] = c.ID;
row["Model"] = c.Model;
row["Status"] = "Offline";
table.Rows.Add(row);
}
dataGridView1.DataSource = table;
I get exception at the first line itself row["Id"]
Column 'Id' does not belong to table .
P.S. I have already added these columns in the designer view of dataGridView.
You just created a blank DataTable and then you are trying to add data to particular columns like Id, Model and Status.
You have to add those columns as well.
DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Model");
table.Columns.Add("Status", typeof(string)); //with type
There is no issue in biding.
Also you can project your required column to an Anonymous type and then bind that to your data grid like:
var result = ctx.ConsumerProducts
.Select(r=> new
{
Id = r.ID,
Model = r.Model,
Status = "Offline"
}).ToList();
dataGridView1.DataSource = result;

Add column to DataTable and move columns to right

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.

Categories