I am working with DataTables. And I have one that is the following:
Ok, what I want to do is for example if I am in the level 1 (COSC-1218-SIT41SCH), I want to get the cell of "Cantidad" of level 2 in red. For example, the cells are C3, C4, C5, C6 and C7. How can I do this with datatables? with .Select or have to use loops? I am completely new with datatables.
First, you can try to get the row index of "COSC-1218-SIT41SCH". And then traverse the DataTable to get "Cantidad". Here is a simple demo you can refer to.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
// Define a list to store the row index of "COSC-1218-SIT41SCH"
List<int> list = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Connection String"))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From GetCellTest", conn);
sda.Fill(ds, "T_Class");
}
dt = ds.Tables["T_Class"];
foreach (DataRow dr in dt.Rows)
{
if (dr["Level1"].ToString() == "COSC-1218-SIT41SCH")
{
list.Add(dt.Rows.IndexOf(dr));
}
}
// Filter the first one
list.Remove(0);
// Get the value of "Cantidad"
foreach(var i in list)
{
Console.WriteLine(dt.Rows[i]["Cantidad"].ToString());
}
}
Related
I have a datagridview that is populated from an sql query. I would like to format the columns that represent a number to N0 (so they have thousand separators), but the method below is not amending the columns.
When I view these columns in the debugger they have a ValueType of Double.
public void DataGridViewFormat(DataGridView dataGrid)
{
foreach (DataGridViewColumn c in dataGrid.Columns)
{
if (c.DefaultCellStyle.Format == "N")
{
c.DefaultCellStyle.Format = "N0";
}
}
}
This is how I am populating the datagridview:
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#ID", int.Parse(comboBox.Text.Split('|')[0]));
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
dataGridView.DataSource = dt;
This is the code I'm working on
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from sometable", con);
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem = new ListViewItem(dr["Col1"].ToString()); // Value is 9999
listitem.SubItems.Add(dr["Col2"].ToString()); // Value is 10
listitem.SubItems.Add(dr["Col3"].ToString()); // Value is 5
listView1.Items.Add(listitem);
}
}
But the output that I'm getting is of the order
Adding listView1.View = View.Details; to the code produces empty listview. How do I get an output that displays the column name and all values ?I'm oblivious to the mistake I'm doing. Any idea where I'm going wrong ?
Try settings listView1.View to View.Details and add 3 proper columns to listView1.Columns in designer:
or in code:
listView.Columns.Clear();
listView.Columns.Add("Col1");
listView.Columns.Add("Col2");
listView.Columns.Add("Col3");
Then, add items this way:
listView.Items.Add(new ListViewItem(new[]
{
dr["Col1"].ToString(),
dr["Col2"].ToString(),
dr["Col3"].ToString()
}));
It always works for me.
Your code may have produced an empty grid because you had no columns.
I'm still learning C# and winform and I can't seem to find a fix to my problem. The problem is whenever I select items in my sql generated checkedlistbox and press the button2 event it won't show the actual data, it just shows "System.Data.DataRowView" am I missing something here is the code..
private void button2_Click(object sender, EventArgs e)
{
int counter = checkedListBox1.SelectedItems.Count;
List<string> selecteditems = new List<string>();
for (int i = 0; i < counter; i++)
{
selecteditems.Add(checkedListBox1.SelectedItems[i].ToString());
}
MessageBox.Show(selecteditems[0]);
for the generation of checkedlistbox here is the code.
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_members ORDER BY Position", con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
DataSet ds = new DataSet();
adapter.Fill(ds);
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.Enabled = true;
checkedListBox1.Refresh();
count = Convert.ToInt32(numericUpDown1.Value);
con.Close();
Try replace your for loop in button2_Click to this:
foreach (DataRowView rowView in checkedListBox1.CheckedItems)
{
selecteditems.Add(rowView["FullName"].ToString());
}
there is both
MessageBox.Show(checkedListBox1.CheckedItems[0].ToString());
and
MessageBox.Show(checkedListBox1.SelectedItems[0].ToString());
use them according to your need I think you were looking for first one
Try using Convert.ToString(checkedListBox1.SelectedItems[i]) instead of .ToString()
.ToString() generally returns variable's class name in string if `.ToString()' not overrided by class.
I have a delete method, it gets an array of GUIDs and I have a data table... how can I filter the data table so it will only contain thoes GUIDs?
public void delete(Guid[] guidlist)
{
datatable template = ReadTemplateList()
...
}
Thank you!
With Linq to DataSet you can create new DataTable which will have only rows with those Guids:
public void Delete(Guid[] guids)
{
DataTable table = ReadTemplateList()
.AsEnumerable()
.Where(r => guids.Contains(r.Field<Guid>("ColumnName")))
.CopyToDataTable();
// ...
}
Another option (which also will work on old .NET versions) is filtering your table with built-in RowFilter functionality which supports IN filters. Let's assume you are filtering by column named ID:
// Check if guids.Length > 0
StringBuilder filter = new StringBuilder("ID IN (");
foreach (Guid id in guids)
filter.AppendFormat("Convert('{0}','System.Guid'),", id);
filter.Append(")");
DataTable template = ReadTemplateList();
DataView view = template.DefaultView;
view.RowFilter = filter.ToString();
DataTable table = view.ToTable();
You can use LINQ:
public static DataTable DeleteGuidsFromTemplate(Guid[] guidlist)
{
DataTable template = ReadTemplateList();
var rowsWithGuids = from row in template.AsEnumerable()
join guid in guidlist
on row.Field<Guid>("Guid") equals guid
select row;
return rowsWithGuids.CopyToDataTable();
}
If you can't use LINQ since you're lower than NET 3.5:
public static DataTable DeleteGuidsFromTemplate(Guid[] guidlist)
{
DataTable template = ReadTemplateList();
DataTable templateGuids = template.Clone();
foreach(DataRow row in template.Rows)
{
Guid guid = (Guid)row["Guid"];
int index = Array.IndexOf(guidlist, guid);
if (index >= 0)
templateGuids.ImportRow(row);
}
return templateGuids;
}
A solution based on DataTable and DataRows.
//fill the datatable from back end
string connStr = ConfigurationManager.ConnectionStrings["ConsoleApplication1.Properties.Settings.NORTHWNDConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand comm = new SqlCommand("select categoryid,categoryname from Categories order by categoryname");
comm.Connection = conn;
SqlDataReader dr = comm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
//datatable filter logic
string[] filter = { "1", "2" };
DataTable filteredTable = dt.Clone();
foreach (string str in filter)
{
DataRow[] filteredRows = dt.Select("categoryid="+ str); //search for categoryID
foreach (DataRow dtr in filteredRows)
{
filteredTable.ImportRow(dtr);
}
}
EDIT
Without going in the for loop
DataTable dt = new DataTable();
dt.Load(dr); //fill the datatable with sqldatareader
DataTable filteredTable = dt.Clone();
DataView dv = dt.DefaultView;
dv.RowFilter = "categoryid in (1,2)";
filteredTable = dv.ToTable();
I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();