how to split the values of column in datatable of dataset? - c#

In my dataset I have many rows,
In first row last column has the value is "12356.56#Firefox 1#23423"
In Second row same column has the value is "12356.56#Chrome2.0#23423"
In Third row same column has the value is "3423#Firefox 14.0#sdfsd"
here instead of displaying same value like above..
I need to display just "Firefox" if that column has Firefox in UI
I need to display just "Chrome" if that column has Chromein UI
how can i do it...

Use this helper function
public static string GetBrowser(string str)
{
str = str.ToUpper();
if(str.Contains("CHROME"))
{
return "Chrome";
}
else if(str.Contains("FIREFOX"))
{
return "Firefox";
}
return "Unknown";
}
Then when you bind the dataset to the UI use it to display the value.

If you have a list of things you want to check for, you can use .Contains to check:
var myValue = myDS[rowIndex][lastColumn].ToString();
if (myValue.Contains("Firefox"))
return "Firefox";
else if (myValue.Contains("Chrome"))
return "Chrome";
else
return "Unknown";
Demo: http://ideone.com/pMVeD
From the examples you've given, it appears the following logic may work, but it should be tested against a wider variety of sample values:
var myValue = myDS[rowIndex][lastColumn].ToString();
var parts = myValue.Split('#');
var browser = parts[1].Split(' ','0','1','2','3','4','5','6','7','8','9');
return browser[0];
Demo: http://ideone.com/NrY1e

Here is code. This might help.
DataSet ds = new DataSet();
//DataTable dt = new DataTable();
ds.Tables.Add("table0");
DataColumn dc = new DataColumn("browser");
ds.Tables[0].Columns.Add(dc);
ds.Tables[0].Rows.Add("12356.56#Firefox1#23423");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string str = ds.Tables[0].Rows[i][0].ToString();
if((str.ToLower().CompareTo("firefox"))!=0)
{
ds.Tables[0].Rows[i][0] = "firefox";
}
}
_gridView.DataSource = ds;
_gridView.DataBind();

Related

DataTable returning empty

For my application there are a few separate dataTables and I need to create a new dataTable based on matching ids. I have to do the process a few times so I created a function so I'm not duplicating code, I've done this like so:
private static DataTable CloneTable(DataTable originalTable, DataTable newTable, DataTable targetTable,
string addedColumn, string columnToExtract, bool multipleConditions = false, string secondColumnName = null, string secondColumnConditon= null)
{
newTable = originalTable.Clone();
newTable.Columns.Add(addedColumn);
foreach (DataRow row in originalTable.Rows)
{
DataRow[] rowsTarget;
if (multipleConditions == false)
{
rowsTarget = targetTable.Select(string.Format("ItemId='{0}'", Convert.ToString(row["ItemId"])));
} else
{
rowsTarget = targetTable.Select(string.Format("ItemId='{0}' AND {1} ='{2}'", Convert.ToString(row["ItemId"]), secondColumnName, secondColumnConditon));
}
if (rowsTarget != null && rowsTarget.Length > 0)
{
string data = rowsTarget[0][columnToExtract].ToString();
var lst = row.ItemArray.ToList();
lst.Add(data);
newTable.Rows.Add(lst.ToArray());
}
else
{
string data = "";
var lst = row.ItemArray.ToList();
lst.Add(data);
newTable.Rows.Add(lst.ToArray());
}
}
return newTable;
}
I then call this in a separate function like so:
private DataTable GetExtractData()
{
.........................
DataTable includeLastModified = new DataTable();
DataTable includeFunction = new DataTable();
DataTable includeDiscipline = new DataTable();
CloneTable(itemsTable, includeLastModified, lastModifiedTable, "LastModifiedDate", "LastModifiedDate");
CloneTable(includeLastModified, includeFunction, customPropertiesTable, "Function", "ItemTitle", true, "Title", "Function");
CloneTable(includeFunction, includeDiscipline, customPropertiesTable, "Discipline", "ItemTable", true, "Title", "Discipline");
return includeDiscipline;
}
The issue I am having is that the dataTable here is returning empty and I am not sure why.
In my CloneTable function I did the following to make sure that the new table is not empty:
foreach (DataRow row in newTable.Rows)
{
foreach (var item in row.ItemArray)
{
Console.WriteLine(item);
}
}
It is not empty so I am not sure why when I'm returning it in a separate function it is now empty?
I call the same thing but for the includeDiscipline table in the GetData function but it comes back empty.
There are no errors but there is a message that comes and goes that says that the parameter "newTable" can be removed as the initial value isn't used. I'm not sure how that could be the case though as it is clearly being used?
I'm assuming that it is probably the way I am calling the function but I'm really not sure what it is that I have done wrong here
Okay face palm moment, just realised I forgot to assign it to something.
So if I do something like:
var test = CloneTable(itemsTable, includeLastModified, lastModifiedTable, "LastModifiedDate", "LastModifiedDate");
return test;
It works fine and no longer returns empty

I need helping adding two different rows(with same columns) to the same datatable

Working on a windows form application that reads in data from csv files and adds the data to a Datagridview. I ran into an issue with all of the rows being added to the datable and being displayed on the datagridview. The datagridview displays the datarows from the first two if conditions and OneRow if condition only. It will not add the rows from the twoRow if condition if the datable and datagridview rows are populated with the OneRow if condition rows. But i want the rows from both OneRow and TwoRow to be displyed. Also the rows from TwoRow do populate the datatable and datagridview when I comment(/**/) out the OneRow if condition. But I need both to populate the table. Thanks in advance!
Construct.MainDataTable.Columns.Add("Date", typeof(DateTime));
Construct.MainDataTable.Columns.Add("Time");
Construct.MainDataTable.Columns.Add("Serial");
Construct.MainDataTable.Columns.Add("Type");
Construct.MainDataTable.Columns.Add("level");
Construct.MainDataTable.Columns.Add("price");
Construct.MainDataTable.Columns.Add(" Limit");
Construct.MainDataTable.Columns.Add("last Limit");
Construct.MainDataTable.Columns.Add("Data");
..........................
...............................................
DataRow oneRow = Construct.MainDataTable.NewRow();
DataRow twoRow = Construct.MainDataTable.NewRow();
dataGridView2.AllowUserToAddRows = false;
if (line.Split(',')[2].Equals("Time"))
{
time = line.Split(',')[3];
date = line.Split(',')[1];
}
if (line.Split(',')[2].Equals("Level"))
{
level = line.Split(',')[3];
}
//OneROw(IF condition)
if ((Convert.ToDecimal(line.Split(',')[8])) < (Convert.ToDecimal (line.Split(',')[12])))
{
type = line.Split(',')[1];
serial = line.Split(',')[7];
price = line.Split(',')[3];
Limit = line.Split(',')[8];
lastLimit = line.Split(',')[10];
Data = line.Split(',')[12];
oneRow["Date"] = date;
oneRow["Time"] = time;
oneRow["Serial"] = serial;
oneRow["Type"] = type;
oneRow["level"] = level;
oneRow["price"] = price;
oneRow[" Limit"] = Limit;
oneRow["last Limit"] = lastlimit;
oneRow["Data"] = Data;
Construct.MainDataTable.Rows.Add(oneRow);
}
//TwoROw(IF condition)
if ((line.Contains('"')) && ((line.Contains("NG"))))
{
price = line.Split(',')[3];
type = line.Split(',')[1];
serial = line.Split(',')[7];
Limit = line.Split('"')[7];
var valLimit = Limit.Split(',').Select(a => Convert.ToInt32(a, 16));
var limitJoin = String.Join(",", valLimit);
lastlimit = line.Split('"')[1];
var vallastLimit = lastlimit.Split(',').Select(d => Convert.ToInt32(d, 16));
var lastJoin = String.Join(",", vallastLimit);
Data = line.Split('"')[5];
var valDatas = Data.Split(',').Select(s => Convert.ToInt32(s, 16));
var dataJoin = String.Join(",", valDatas);
twoRow["Date"] = date;
twoRow["Time"] = time;
twoRow["Serial"] = serial;
twoRow["Type"] = type;
twoRow["level"] = level;
twoRow["price"] = price;
twoRow["Limit"] = limitJoin;
twoRow["last Limit"] = lastJoin;
twoRow["Data"] = dataJoin;
Construct.MainDataTable.Rows.Add(twoRow);
}
dataGridView2.DataSource = Construct.MainDataTable;
Can't add a comment because I don't have enough karma so I ask my questions here: So, if I understood your problem you can't add data from one .csv file if it have more then one row? Why are you using 2 different if conditions for row in .csv file?
If you have empty data in row never mind you can still place them to your DataTable column, so you can use loop to add data from .csv to your DataTable. Try some thing like this:
public static DataTable CsvToDataTable(string csv)
{
DataTable dt = new DataTable();
string[] lines = csv.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
Regex onlyDeimiterComma = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
for (int i = 0; i < lines.Length; i++)
{
DataRow row = dt.NewRow();
string[] cells = onlyDeimiterComma.Split(lines[i]);
for (int j = 0; j < cells.Length; j++)
{
if (i == 0)
{
if (j == 0)
{
dt.Columns.Add(cells[j], typeof(DateTime));
}
else
{
dt.Columns.Add(cells[j]);
}
}
else
{
row[j] = cells[j];
}
}
dt.Rows.Add(row);
}
return dt;
}
Just call this method anywhere in your code and give it string read from your .csv file.
You can try to compile this code here and see how it works on .csv data with different data (empty columns, quoted text, quoted commas)
UPD: If you need to fill DataTable from two different .csv files you can still use code above. Just call it twice for both files and then Merge two DataTable, like this:
DataTable dt = CsvToDataTable(csvFileOne);
DataTable dtTwo = CsvToDataTable(csvFileTwo);
dt.Merge(dtTwo);

Datagrid filter on column that between two age range

I have a datagridview with a column of type string that display values for age ranges such as:
0-18
19-100
0-100
I also have a filter textbox that would need to filter on the age range
(dgv1.DataSource as DataTable).DefaultView.RowFilter =
string.Format("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text);
The problem is that if the user enter a number like 18, the grid does not return row for 0-100
How can I get the datagrid to return both 0-18 and 0-100?
I do not think you will be able to do this using the “LIKE” comparator since the values you are looking for are “numeric”. To get the filter you are looking for, you will need a filter with “>=” and “<=” to see if the target age is in the range. It is unclear how the data is originally received, if the “age range” in each row is a string as shown, then I suggest a couple of different hacky ways. In addition, it is unclear what other columns would be in the grid.
One “hacky” approach, would be to make a method that returns a new DataTable with only the rows that fall into the given target range. To help in this endeavor, a second method that takes an int (target value we are looking for), and a DataRowView (The AgeRange we are comparing the “target” value to). This “AgeRange” will be in the rows first column. Here we simply take that string range (“0-18”) and the target value (“18”) to see if this target value IS in the range, then return true or false depending on the result. This can be done using the string.split method to split the “AgeRange” string and int.TryParse to convert the strings into numbers. Below is an example of this.
private bool TargetIsInRange(int target, DataRowView row) {
if (row.Row.ItemArray[0] != null) {
string cellValue = row.Row.ItemArray[0].ToString();
string[] splitArray = cellValue.Split('-');
int startValue;
int endValue;
if (!int.TryParse(splitArray[0], out startValue)) {
return false;
}
if (!int.TryParse(splitArray[1], out endValue)) {
return false;
}
if (target >= startValue && target <= endValue)
return true;
}
return false;
}
The method above should come in handy when looping through the grids rows to figure out which rows go into the new filter DataTable. Next, a method that does this looping through the grid and returns a filtered DataTable. For each row in the grid, we could call the above method and add the rows that return true.
private DataTable GetFilterTable() {
DataTable filterTable = ((DataTable)dgv1.DataSource).Clone();
dgv1.DataSource = gridTable;
int targetValue = -1;
if (int.TryParse(textBox1.Text, out targetValue)) {
foreach (DataGridViewRow row in dgv1.Rows) {
DataRowView dataRow = (DataRowView)row.DataBoundItem;
if (dataRow != null) {
if (TargetIsInRange(targetValue, dataRow)) {
filterTable.Rows.Add(dataRow.Row.ItemArray[0]);
}
}
}
}
return filterTable;
}
It is unclear where you are calling this filter, if you are filtering “strings” then as the user types the filter string in the text box the grid will filter with each character pressed by the user. This is nice with strings, however, in this case using “numbers”, I am guessing a button would be more appropriate. I guess this is something that you will have to decide. Putting all this together using a Button click event to signal when to filter the grid may look something like below
private DataTable gridTable;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
gridTable = GetTable();
FillTable(gridTable);
dgv1.DataSource = gridTable;
textBox1.Text = "18";
}
private void FillTable(DataTable dt) {
dt.Rows.Add("0-18");
dt.Rows.Add("19-100");
dt.Rows.Add("0-100");
dt.Rows.Add("17-80");
dt.Rows.Add("18-80");
}
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
return dt;
}
private void button1_Click(object sender, EventArgs e) {
if (textBox1.Text == "") {
dgv1.DataSource = gridTable;
return;
}
dgv1.DataSource = GetFilterTable();
}
Hacky Approach 2
The first approach works; however, I am guessing if there is a LOT of data and a LOT of filtering, this may become a performance issue. Therefore, in this approach, extra steps are taken in the beginning to take advantage of the DataTables RowFilter feature, as the posted code is doing. Obviously as stated previously, we will not use the “LIKE” comparator, instead the “<=” and “>=” operators are used.
In order to accomplish this, we MUST somehow turn the given string range “XX-XX” into two (2) ints. Then “add” these integers to the DataTable. Then it will be easy to filter the table using the RowFilter property and the less than and greater than operators. One problem is that it will require “extra” work on our part to set up the grid’s columns properly or these extra two columns of data will also display.
This can be done in the “designer” or manually in code. Without going into too much detail, it is useful to bear in mind that IF you assign a DataTable as a data source to the grid AND you set the grids AutoGenerateColumns property to false… THEN only the grid columns with DataPropertyName names that “match” one of the DataTable column names… will display. In this case, we only want the AgeRange column with the “XX-XX” strings to display, the other two new columns can remain hidden from the user. Setting up the grid column manually may look something like below, however you can do this in the designer. NOTE: the designer does not display an AutoGenerateColumns property, you have to do this in your code.
private void AddGridColumn() {
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "AgeRange";
col.DataPropertyName = "AgeRange";
col.HeaderText = "Age Range";
dgv1.Columns.Add(col);
}
The important point is that the DataPropertyName MUST match the target column name in the DataTable, otherwise the column will not display.
Next is the construction of the new DataTable. This method is given the original DataTable. A new DataTable is created with three (3) columns, AgeRange-string (displayed), StartRange-int and EndRange-int. The start and end columns will not be displayed. Once this new table is constructed, a foreach loop is started through all the rows in the original table. The string digits from the original tables row are “parsed” into actual numbers and added to the new DataTable along with the original “range” string. This method could look something like below. A helper method is further below to help split the age range string and return a number.
private DataTable GetSplitTable(DataTable sourceTable) {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
dt.Columns.Add("StartRange", typeof(int));
dt.Columns.Add("EndRange", typeof(int));
foreach (DataRow row in sourceTable.Rows) {
int startValue = GetIntValue(row.ItemArray[0].ToString(), 0);
int endValue = GetIntValue(row.ItemArray[0].ToString(), 1);
dt.Rows.Add(row.ItemArray[0], startValue, endValue);
}
return dt;
}
private int GetIntValue(string rangeString, int index) {
string[] splitArray = rangeString.Split('-');
int value = 0;
int.TryParse(splitArray[index], out value);
return value;
}
Putting all this together may look like below. Note, the button click event checks to see if the text box is empty, and if it is, will remove the current filter if one is applied.
private DataTable gridTable;
private DataTable splitTable;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
gridTable = GetTable();
FillTable(gridTable);
splitTable = GetSplitTable(gridTable);
AddGridColumn();
dgv1.AutoGenerateColumns = false;
dgv1.DataSource = splitTable;
textBox1.Text = "18";
}
private void FillTable(DataTable dt) {
dt.Rows.Add("0-18");
dt.Rows.Add("19-100");
dt.Rows.Add("0-100");
dt.Rows.Add("17-80");
dt.Rows.Add("15-75");
}
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("AgeRange", typeof(string));
return dt;
}
private void AddGridColumn() {
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "AgeRange";
col.DataPropertyName = "AgeRange";
col.HeaderText = "Age Range";
dgv1.Columns.Add(col);
}
private void button1_Click(object sender, EventArgs e) {
string filterString = "";
DataView dv;
if (textBox1.Text != "") {
filterString = string.Format("StartRange <= {0} AND EndRange >= {0}", textBox1.Text);
}
dv = new DataView(splitTable);
dv.RowFilter = filterString;
dgv1.DataSource = dv;
}
This Code:
("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text)
is a redundant with two AgeRange LIKE
If you want to search like textBoxFilter.Text you can try
("AgeRange LIKE '%{0}%'", textBoxFilter.Text)
Or
StringBuilder rowFilter = new StringBuilder();
rowFilter.Append("AgeRange Like '%" + textBoxFilter.Text + "%'");
(dgv1.DataSource as DataTable).DefaultView.RowFilter = rowFilter.ToString();

Convert DataGrid to DataTable

What's the equivalent in .NET to convert my DataGrid to a DataTable (DataGrid.ItemsSource isn't defined in .Net csharp.
Thanks!
DataTable dt = new DataTable();
dt = ((DataView)DataGrid1.ItemsSource).ToTable();
EDIT
This isn't a duplicate since the previous code is for WPF and I'm looking for an asp.net mvc csharp answer.
The ItemsSource is for WPF. Use the DataSource and cast it to DataTable like this:
dt = (DataTable)DataGrid1.DataSource;
EDIT: And if you get into trouble with above approach, you can use a custom method like this:
private DataTable ToDataTable(DataGridView dataGridView)
{
var dt = new DataTable();
foreach (DataGridViewColumn dataGridViewColumn in dataGridView.Columns)
{
if (dataGridViewColumn.Visible)
{
dt.Columns.Add();
}
}
var cell = new object[dataGridView.Columns.Count];
foreach (DataGridViewRow dataGridViewRow in dataGridView.Rows)
{
for (int i = 0; i < dataGridViewRow.Cells.Count; i++)
{
cell[i] = dataGridViewRow.Cells[i].Value;
}
dt.Rows.Add(cell);
}
return dt;
}
And then use it:
var dataTable = ToDataTable(dataGridView1);
Also MoreLinq is a good choice in case the type of Datasource is a list. Check this solution to know how to use it: https://stackoverflow.com/a/42550827/2946329
If you are referring to the System.Windows.Forms.DataGrid or System.Web.UI.WebControls.DataGrid, then the best way would be to cast the Datasource property to a DataTable.
Of course the Datasource property has to actually be a DataTable underlying type to begin with. You need to know the underlying type of the object stored in the Datasource property.
If the underlying type of Datasource is a generic list, then this SO post should help: How to convert a list into data table
FYI - The Windows Forms DataGrid control, according to Microsoft, has been replaced by the DataGridView.
if there is visible columns in datagridview you can use
private DataTable ToDataTable(DataGridView dataGridView)
{
var dt = new DataTable();
int columnCount = 0;
List<int> columnNumbers= new List<int>();
foreach (DataGridViewColumn dataGridViewColumn in dataGridView.Columns)
{
if (dataGridViewColumn.Visible)
{
dt.Columns.Add(dataGridViewColumn.Name);
columnNumbers.Add(columnCount);
}
columnCount++;
}
var cell = new object[columnNumbers.Count];
foreach (DataGridViewRow dataGridViewRow in dataGridView.Rows)
{
int i = 0;
foreach (int a in columnNumbers)
{
cell[i] = dataGridViewRow.Cells[a].Value;
i++;
}
dt.Rows.Add(cell);
}
return dt;
}
The custom method does not take into account the hidden columns. You are getting an error, because you have too many cells for the columns copied.
You can use :
int dgv1RowCount = dgv1.Rows.Count;
int numOfColumns = dgv1.Columns.GetColumnCount(DataGridViewElementStates.Visible) ;
int numCells = dgv1RowCount * numOfColumns;
// use numCells in the for loop
for (int i = 0; i < numOfCells ; i++)
{
enter code here
}

Compare dataset column type

Here's the code :
try
{
string strReadDataLine;
strReadDataLine = sr.ReadLine();
while (strReadDataLine != null)
{
string[] strReadDataLineSplited = strReadDataLine.Split(';');
DataRow thisRow = thisDataSet.Tables["Repartition"].NewRow();
DataTable item = thisDataSet.Tables["Repartition"];
for (int i = 0; i < strDataLines.Length; i++)
{
DataColumn thisColomn =
thisDataSet.Tables["Repartition"].Columns[i];
// Here i need to know if the colomn is a string
if (thisColomn.DataType.ToString() == "System.String")
{
thisRow[strDataLines[i]] = strReadDataLineSplited[i];
}
}
thisRow["ID_USAGER"] = 1;
thisDataSet.Tables["Repartition"].Rows.Add(thisRow);
strReadDataLine = sr.ReadLine();
}
//thisDataAdapter.Update(thisDataSet, "Repartition");
}
What I need is to know if a column is a string to assign a data as string to the column. What I get is a argumentException saying "input string was not in correct format. couldn't store <2.111> in MY_FLOAT colomn. Expect type is double."
What I really need is to compare the column type to something to get the type then assign the column to the correct type.
I hope this is clear as my English is not so good.
If I understand correctly I built a functional copy of the code-fragment and fixed it to correctly handle the type conversion. You really only missed two things:
. #1 - You were indexing into the columns by ordinal and using that information to obtain the column type. Then setting the information you indexed the column my name. I corrected this with the introduction of the 'columnName' variable below.
. #2 - To properly convert the string input to the desired column type you only need to use the System.Convert.ChangeType(object, Type) method as shown below.
static void Main()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Repartition");
DataColumn col;
col = dt.Columns.Add("ID_USAGER", typeof(int));
col = dt.Columns.Add("TestString", typeof(string));
col = dt.Columns.Add("TestInt", typeof(int));
col = dt.Columns.Add("TestDouble", typeof(double));
string testData = "TestString;TestInt;TestDouble";
testData += Environment.NewLine + "Test1;1;1.1";
testData += Environment.NewLine + "Test2;2;2.2";
Test(ds, new StringReader(testData));
}
public static void Test(DataSet thisDataSet, StringReader sr)
{
string[] strDataLines = sr.ReadLine().Split(';');
string strReadDataLine;
strReadDataLine = sr.ReadLine();
while (strReadDataLine != null)
{
string[] strReadDataLineSplited = strReadDataLine.Split(';');
DataRow thisRow = thisDataSet.Tables["Repartition"].NewRow();
DataTable item = thisDataSet.Tables["Repartition"];
for (int i = 0; i < strDataLines.Length; i++)
{
string columnName = strDataLines[i];
//#1 Don't use this as Columns[i] may not be Columns[columnName]
//DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[i];
DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[columnName];
//#2 Assing to the results of the string converted to the correct type:
thisRow[strDataLines[i]] = System.Convert.ChangeType(strReadDataLineSplited[i], thisColomn.DataType);
}
thisRow["ID_USAGER"] = 1;
thisDataSet.Tables["Repartition"].Rows.Add(thisRow);
strReadDataLine = sr.ReadLine();
}
}

Categories

Resources