from datatable to array، no loop - c#

Following Code for transmission to the list box is :
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
var Query = from mycolumn in dt.AsEnumerable()
where mycolumn.Field<string>("BestSite") != string.Empty
select mycolumn;
listBox1.DataSource = Query.AsDataView();
listBox1.DisplayMember = "BestSite";
Transfer to array what should be? no loop
string[] myvalue = new string[Query.AsDataView().Count];

Finally realized
Correct answer :
private string ConvertToString(DataRow dr)
{
return Convert.ToString(dr[0]);
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
//var Query = from mycolumn in dt.AsEnumerable()
// where mycolumn.Field<string>("BestSite") != string.Empty
// select mycolumn;
DataRow[] myrow = new DataRow[dt.Rows.Count];
dt.Rows.CopyTo(myrow, 0);
string[] myString = Array.ConvertAll(myrow, new Converter<DataRow, string>(ConvertToString));
foreach (string a in myString)
{
listBox1.Items.Add(a);
}
}

If I understood your question correctly...
string[] myvalue = Query.Select(i => i.Field<string>("BestSite")).ToArray();

This example assumes:
=> datatable is non zero length
=> values are "parsable" to double.
coln = "PurchasePrice";
double[] arr_val = Array.ConvertAll<DataRow, double>
(
dattbl.Select(),
delegate (DataRow rw) { return
double.Parse(rw[coln].ToString()); }
);
// ... and for example
double total = arr_val.Sum();

Related

Adding a rank column to a data table after sorting it

i am trying to add a new column to a data table that is the rank. For that I want to loop through each row after sorting and then assign a rank to each row starting at 1.
Below is my code. However The rank is getting assigned to the row before the sort it looks like.
So my rank calculation is not doing what its supposed to do. Is it possible to add a rank this way?
protected void bindGridView(GridView gv)
{
using(DataTable dt = getData())
{
DataColumn dc_Total = new DataColumn("Total");
DataColumn dc_Rank = new DataColumn("Rank");
dt.Columns.Add(dc_Total);
dt.Columns.Add(dc_Rank);
dc_Rank.SetOrdinal(1);
dc_Total.SetOrdinal(2);
foreach (DataRow dr in dt.Rows)
{
dr["Total"] = Convert.ToDouble(dr["A_B_PERC"].ToString()) + Convert.ToDouble(dr["C_PERC"].ToString());
}
dt.DefaultView.Sort = "Total";
int rank = 1;
foreach(DataRow dr in dt.Rows)
{
dr["Rank"] = rank;
rank++;
}
gv.DataSource = dt;
gv.DataBind();
}
}
Below is the result I'm getting:
What I really want is:
I was able to fix my problem with the code below:
protected void bindGridView(GridView gv)
{
using(DataTable dt = getData())
{
DataColumn dc_Total = new DataColumn("Total");
DataColumn dc_Rank = new DataColumn("Rank");
dt.Columns.Add(dc_Total);
dt.Columns.Add(dc_Rank);
dc_Rank.SetOrdinal(1);
dc_Total.SetOrdinal(2);
foreach (DataRow dr in dt.Rows)
{
dr["Total"] = Convert.ToDouble(dr["A_B_PERC"].ToString()) + Convert.ToDouble(dr["C_PERC"].ToString());
}
dt.DefaultView.Sort = "Total";
using(DataView dv = dt.DefaultView)
{
int rank = 1;
foreach (DataRowView drv in dv)
{
drv["Rank"] = rank;
rank++;
}
gv.DataSource = dv;
gv.DataBind();
}
}
}
Hope this helps if anyone else is having similar issue.

check if word exist in table

i have built a datatable as in picture .. i shall inter sentence in a textbox such as: "the boy kick the ball " i need to check each word of that sentence if it does exist in that table so it will display the name of the column that contains the word in a listbox such as:(the => Article).
i did all the steps but i stops in the last step of checking and displaying the name of the column that contains the word..
i'm just a beginner so it becomes hard to me to programming the last steps would any one help me please???
datatable has three columns "Article","Noun","verb"
and rows values:"the","boy","kick" and so on in other rows
DataTable dt = new DataTable();
DataColumn article = new DataColumn("Article", typeof(string));
dt.Columns.Add(article);
DataColumn noun = new DataColumn("Noun", typeof(string));
dt.Columns.Add(noun);
DataColumn verb = new DataColumn("Verb", typeof(string));
dt.Columns.Add(verb);
DataRow dr = dt.NewRow();
dr["Article"] = "the";
dr["Noun"] = "boy";
dr["Verb"] = "kick";
dt.Rows.Add(dr);
dr = dt.NewRow();
DataRow dd = dt.NewRow();
dd["Article"] = "a";
dd["Noun"] = "ball";
dd["Verb"] = "eat";
dt.Rows.Add(dd);
dd = dt.NewRow();
dataGridView1.DataSource = dt;
string s = textBox1.Text;
string[] st = s.Split(' ');
now how to check each word in st[] if it does exist in the table
he will display the word and the name of the column he found it in
Hope it helps
using System;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
DataColumn article = new DataColumn("Article", typeof(string));
dt.Columns.Add(article);
DataColumn noun = new DataColumn("Noun", typeof(string));
dt.Columns.Add(noun);
DataColumn verb = new DataColumn("Verb", typeof(string));
dt.Columns.Add(verb);
DataRow dr = dt.NewRow();
dr["Article"] = "the";
dr["Noun"] = "boy";
dr["Verb"] = "kick";
dt.Rows.Add(dr);
dr = dt.NewRow();
DataRow dd = dt.NewRow();
dd["Article"] = "a";
dd["Noun"] = "ball";
dd["Verb"] = "eat";
dt.Rows.Add(dd);
dd = dt.NewRow();
string s = "the boy eat the ball"; //textBox1.Text;
string[] st = s.Split(' ');
foreach (var str in st)
{
foreach (DataRow rows in dt.Rows)
{
if(str == rows["Article"].ToString())
Console.WriteLine("Word=" + str + " Column=Article");
else if (str == rows["Noun"].ToString())
Console.WriteLine("Word=" + str + " Column=Noun");
else if (str == rows["Verb"].ToString())
Console.WriteLine("Word=" + str + " Column=Verb");
}
}
}
}
}
Output:
Word=the Column=Article
Word=ball Column=Noun
Word=eat Column=Verb
Word=a Column=Article
Word=boy Column=Noun

How to create datatable in C#?

I tried create and fill a simple DataTable
Result of this code :
Order Driver
1
1
But I want to show on same row like this :
Order Driver
1 1
Where is my wrong in this code ?
public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
if(AnotherMethod1(Param))
{ dr = dt.NewRow();
dr["Order"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Order"] = 0;
dt.Rows.Add(dr);
}
if(AnotherMethod2(Param))
{ dr = dt.NewRow();
dr["Driver"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Driver"] = 0;
dt.Rows.Add(dr);
}
return dt;
}
You're adding a row every time you set value to a different column.
Try this:
public DataTable MethodName(string Param)
{
DataTable dt = new DataTable();
dt.Columns.Add("Order", typeof(Int32));
dt.Columns.Add("Driver", typeof(Int32));
DataRow dr = dt.NewRow();
dr["Order"] = AnotherMethod1(Param) ? 1 : 0;
dr["Driver"] = AnotherMethod2(Param) ? 1 : 0;
dt.Rows.Add(dr);
return dt;
}
public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
dr = dt.NewRow();
if(AnotherMethod1(Param))
{
dr["Order"] = 1;
}
else
{
dr["Order"] = 0;
}
if(AnotherMethod2(Param))
{
dr["Driver"] = 1;
}
else
{
dr["Driver"] = 0;
}
dt.Rows.Add(dr);
return dt;
}

DataTable row filling in C#

I am trying to add row in DataTable CartDT using row[], which is a string array.
DataTable CartDT = new DataTable();
public void DataTableColumn()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
string[] row = new string[5];
row[0] = arg[0]; //Product_Name
row[1] = arg[1]; //Product_ID
row[2] = itemQuantity.Text; //OrderQTY
row[3] = arg[2]; //Price
row[4]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Now when I execute it, it gives the error that "Input array is longer than the number of columns in this table"
The array row[] has exactly 5 elements in it & also DataTable CartDT has also 5 columns.
Now i am not able to find exactly where i am wrong.
Please help me to find the bug.
Thanx in advance.
Instead do this
DataRow dr = CartDT.NewRow();
Then
dr[0] = arg[0];
and so on. In the end
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
This way the instance of Row will have CartDT schema.
DataTable CartDT = new DataTable();
public void CreateDataTableColumns()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
if (CartDT.Columns.Count = 0)
{
CreateDataTableColumns();
}
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity =
(TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow dr = CartDT.NewRow();
dr[0] = arg[0]; //Product_Name
dr[1] = arg[1]; //Product_ID
dr[2] = itemQuantity.Text; //OrderQTY
dr[3] = arg[2]; //Price
dr[4] = (Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString(); // calculate total price
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Debug, and break on
CartDT.Rows.Add(row);
and see how many columns are in CartDT; I think you don't call DataTableColumn() at the right time.
Your code having to do with row insertion works just fine
DataTable CartDT = new DataTable();
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
string[] row = new string[5];
row[0] = "1"; //Product_Name
row[1] = "2"; //Product_ID
row[2] = "3"; //OrderQTY
row[3] = "4"; //Price
row[4] = "5";// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
for (int i = 0; i < 5; i++)
{
Console.WriteLine(CartDT.Rows[0][i]);
}
Console.Read();
Try Below Code:
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow row = CartDT.NewRow();
row["Product_Name"] = arg[0]; //Product_Name
row["Product_ID"] = arg[1]; //Product_ID
row["OrderQTY"] = itemQuantity.Text; //OrderQTY
row["Price"] = arg[2]; //Price
row["TotalPrice"]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();
CartDt.Rows.Add(row);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}

Merge datatables but ignore duplicated rows

I have the following code, its a custom people picker for sharepoint 2010.
It searches by username, but also by the person name.
Because its a contains search, if I try with part of my username: cia
It shows my duplicated rows because that matches the username but also the person name.
this is my code (I cant use LINQ:
protected override int IssueQuery(string search, string groupName, int pageIndex, int pageSize)
{
try
{
// Find any user that has a matching name
var table = ADHelper.ExecuteNameQuery(RootPath, search);
// 20249: Search by username, method was already done, but it was not being called.
var table2 = ADHelper.ExecutesAMAccountNameQuery(search);
table2.Merge(table,);
PickerDialog.Results = table2;
Normally the DataTable.Merge method removes duplicates implicitely. But only when all columns' values are the same.
I'm not sure if there is something simplier(you've mentioned that you cannot use LINQ), but you could merge both and remove the duplicates afterwards:
List<string> dupColumns = new List<string>();
dupColumns.Add("ColumnA");
dupColumns.Add("ColumnB");
table2.Merge(table,);
RemoveDuplicates(table2, dupColumns);
And here the remove-duplicates function:
private void RemoveDuplicates(DataTable table, List<string> keyColumns)
{
Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(table.Rows.Count);
System.Text.StringBuilder sb = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table.Rows;
while (rowIndex < rows.Count)
{
row = rows[rowIndex];
sb = new System.Text.StringBuilder();
foreach (string colname in keyColumns)
{
sb.Append(((string)row[colname]));
}
if (uniquenessDict.ContainsKey(sb.ToString()))
{
rows.Remove(row);
}
else
{
uniquenessDict.Add(sb.ToString(), string.Empty);
rowIndex++;
}
}
}
you should the .ToTable function
here is a sample code
DataTable DT1 = new DataTable();
DT1.Columns.Add("c_" + DT1.Columns.Count);
DT1.Columns.Add("c_" + DT1.Columns.Count);
DT1.Columns.Add("c_" + DT1.Columns.Count);
DataRow DR = DT1.NewRow();
DR[0] = 0;
DR[1] = 1;
DR[2] = 2;
DT1.Rows.Add(DR);
DataTable DT2 = new DataTable();
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DR = DT2.NewRow();
DR[0] = 0;
DR[1] = 1;
DR[2] = 2;
DR[3] = 3;
DT2.Rows.Add(DR);
DT1.Merge(DT2);
Trace.IsEnabled = true;
DataTable DT_3=DT1.DefaultView.ToTable(true,new string[]{"c_1","c_2","c_0"});
foreach (DataRow CDR in DT_3.Rows)
{
Trace.Warn("val",CDR[1]+"");//you will find only one data row
}

Categories