I have a DataGridView with a source of DataSet filled by Adapter using data from Database. Now I want to query the DataSet with closed connection. What is the query to search a specific record?
This is the code that fetches all customers:
private void button2_Click(object sender, EventArgs e)
{
DataSet CustList = new DataSet();
CustList = gt.GetCustomers();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = CustList.Tables[0];
}
What will be done to query this DataSet CustList and throw the results back in the same DGV, Thanks.
Try this..
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
[Reference]
Related
I have asked a similar question here but in my case I need to store multiple sets of datasets for an unknown number of times, not just once. So that is why I am asking here again.
I have multiple datatables with 2 columns in each datatable. One of them is a bool column (checkbox values). The checkbox values are empty when the form loads so up to user to check or uncheck them. Upon updating the checkbox, user press button1 to save only checkbox values in a dataset and this dataset will be saved in a List.
These datatables will then empty out and the same steps repeat for an unknown number of times (form loads empty datatables, user update checkboxes, user press button1). I have used the method below. No errors but when I want to display the List value in datagridview1 in Form2, it was empty. Below is my code. Hope to get help, thanks!
Class 1.cs (where I initiated my List)
public static List<string> list = new List<string>();
Form1.cs
//Create dataset
private DataSet Getdataset()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
DataTable dt2 = new DataTable();
dt2.Columns.Add("Items", typeof(string));
dt2.Columns.Add("Status", typeof(bool));
dt2.Rows.Add("bye");
dt2.Rows.Add("bye");
ds.Tables.Add(dt2);
dgv2.DataSource = dt2;
dgv2.AllowUserToAddRows = false;
return ds;
}
//Save dataset in a List
private void button1_Click(object sender, EventArgs e)
{
DataSet dd = Getdataset();
foreach (DataTable table in dd.Tables)
{
foreach (DataRow row in table.Rows)
{
Class1.list.Add(Convert.ToString(row["Status"]));
}
}
Form2 f = new Form2();
f.ShowDialog();
}
Form2.cs
//Display dataset in datagridview
private void compile_VisibleChanged(object sender, EventArgs e)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
foreach (string item in Class1.list)
{
row.Cells[0].Value = item;
}
dataGridView1.Rows.Add(row);
}
EDIT
As per er-sho comment, I added a messagebox in the code per below and it showed Systems.Collection.Generic.List1[System.String] 7 times (I have 6 checkboxes). There was still no display in the datagridview1 and I initialized the no. of columns, headers for datagridview1 to avoid compilation error. However, see below comment under Gokham’s solution (seems like the data in List is not per expected)
foreach (string item in Class1.list)
{
MessageBox.Show(Class1.list.ToString());
row.Cells[0].Value = item;
}
Everytime, when you click button1, you rewrite your data in dgv1 with default values:
DataTable dt1 = new DataTable();
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
dgv1.DataSource = dt1;
dt1 will be contains rows with only Item values, but not with Status. You should add code with getting user inputs
UPDATE
To achieve the goal you should make follow steps:
Init dgv1 - add columns and fill rows with default values
private void Form1_Load(object sender, EventArgs e)
{
UpdateDgv1();
}
private void UpdateDgv1()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
}
Get values from dgv1 on button click
private void button1_Click(object sender, EventArgs e)
{
for (var i = 0; i < dgv1.Rows.Count; i++)
{
list.Add(Convert.ToString(dgv1.Rows[i].Cells[1].Value));
}
//restore dgv1
UpdateDgv1();
Form2 f = new Form2();
f.ShowDialog();
//clear list with old values or comment it
//if you want to save history of user inputs
list.Clear();
}
Show list content on datagridview1 of Form2
private void Form2_VisibleChanged(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 1;
foreach (string item in Form1.list)
{
var newRow = dataGridView1.Rows.Add();
//if checkbox from Form1 not checked
if (item == string.Empty)
dataGridView1.Rows[newRow].Cells[0].Value = false.ToString();
else
dataGridView1.Rows[newRow].Cells[0].Value = item;
}
}
Your Getdataset() method doesn't fill Status column of the table. Try
private DataSet Getdataset()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
DataRow dr = dt1.NewRow();
dr["Items"] = "Hello";
dr["Status"] = checkBox1.Checked;
dt1.Rows.Add(dr);
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
...
return ds;
}
I recommend you using BindingList instead of List and assigning the list as the DataSource for dataGridView1.
public static BindingList<string> list = new BindingList<string>();
Form 2
private void compile_VisibleChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = Class1.list;
}
I think using FormLoad event handler instead of VisibleChanged should be better in your case.
Have a look : Binding List<T> to DataGridView in WinForm
I have datagridview which displays it's data source (SQL database for an inventory system).
What I would like to be able to do is filter what is shown in the datagridview based on if something has been ordered etc...
So I am filling the datagridview like this:
private void Form1_Load(object sender, EventArgs e)
{
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
ResizeCols();
}
but I can't for the life of me figure out how to query the dataset.
For instance I would like to click a button and that would display all rows in which the ordered column has been checked.
But in general I would like to know how to build my own queries.
You can use a DataView for the above purpose and bind the filtered DataView to the DataGrid.
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
DataView dv = new DataView(bUZZGEEF_DBDataSet.BG_T1);
dv.RowFilter = "query"; // query example = "id = 10"
myDataGridView.DataSource =dv;
For more information, You can look here
You can use the DataTableView RowFilter to query a datatable
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
bUZZGEEF_DBDataSet.BG_T1.DefaultView.RowFilter = "ID < 10";
myDataGridView.DataSource =bUZZGEEF_DBDataSet.BG_T1.DefaultView;
https://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter(v=vs.110).aspx
I think you want something like what you see in the code sample below. Basically, start typing in the TextBox, and the results in the GridView will be filtered, relative to what is entered into the TextBox.
using System.Data.SqlClient;
public class Form1
{
DataSet ds = new DataSet;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=name_of_your_sql_server; Integrated Security=true; Initial Catalog=name_of_your_database");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Categories", con);
da.Fill(ds, "Cat");
DataGridView1.DataSource = ds.Tables("Cat");
}
private void TextBox1_TextChanged(System.Object sender, System.EventArgs e)
{
ds.Tables("Cat").DefaultView.RowFilter = "[CategoryName] LIKE '*" + TextBox1.Text + "*'";
}
}
I have filled dataset with this data now I want to pick particular column from it but based on condition, I don't want to connect database each time just picking from dataset would be great.
So how can I apply condition on dataset like where clause etc?
Dataset
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet dss = CalendarSpotting();
Session["Calendar"] = dss;
}
}
protected void Calndar_SelectionChanged(object sender, EventArgs e)
{
DataSet ds = (DataSet)Session["Calendar"];
}
What i like to do is:
DataTable theTable = dataSet.Tables[0];
Or:
DataTable theTable = dataSet.Tables["YourTableName"];
Which makes it much easier to loop through columns and rows in my
experience.Like this:
if(theTable.Rows[0]["YourColumnName"].toString() == "Itsmee")
{
// do this, do that
}
I have a Database with 2 Tables. Now i want to search for Values in my Databases.
I use this GUI so the "User" can give Information to the Textbox and the searched Values should shown in my Datagridview
I use this Code:
private void TB_MSGHeadline_TextChanged(object sender, EventArgs e)
{
try
{
if (TB_MSGHeadline.Text.Equals(""))
{
}
else
{
DataView dv = new DataView(table);
dv.RowFilter = string.Format("MessageHeadline LIKE '%{0}%'", TB_MSGHeadline.Text);
dataGridView1.DataSource = dv;
}
}
catch (Exception i)
{
MessageBox.Show("" + i);
}
}
Fill the DataGridview
private void GetData(string selectCommand)
{
//Creating a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, ConnectionString);
//Create a command builder to generate SQL update, insert, and
//delete commands based on selectCommand. These are used to
//update the Database.
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder();
//Populate a new data table and bind it to the BindingSource
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
BindingSource1.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = BindingSource1;
GetData("SELECT * FROM Tabelle1");
}
(Found it in a video but dont work for my problem)
But i get the Error, that the row "MessageHeadline" wasnt found
So i want to know, how can i make a LIKE search for my SQL Database?
I am trying to show data from DataTable into GridView using a LINQ query but I am not able to understand that why this code is not working. Actually GridView shows RowError HasError message. I am totally confused.
Here's my code
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = (DataTable)Session["userTable"];
string compare = Request.QueryString["id"].ToString();
var data = from x in table.AsEnumerable()
where x.Field<string>("Userid") == compare
select x;
GridView1.DataSource = data;
GridView1.DataBind();
}
Your query returns IEnumerable<DataRow> to convert it to Datatble use CopyToDataTable() extension. MSDN
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = (DataTable)Session["userTable"];
string compare = Request.QueryString["id"].ToString();
IEnumerable<DataRow> data = from x in table.AsEnumerable()
where x.Field<string>("Userid") == compare
select x;
DataTable boundTable = data.CopyToDataTable<DataRow>();
GridView1.DataSource = boundTable;
GridView1.DataBind();
}
Try this,
var data = from x in table.AsEnumerable()
where x.Field<string>("UserId").ToUpper().ToString().Equals(compare.ToUpper().ToString())
select x;
DataTable boundTable = data.AsDataView().ToTable();
return boundTable;