I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}
Related
i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.
Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me
Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
I'm trying to filter a datagridview that has been bound to a dataset. The thing is, when I type data into my textbox, the app stops and the error is that the column I'm trying to filter doesn't exist. I tried populating the datagridview with a string query and filtering works properly, but I can't update the datagridview (I don't know why). That's why I'm populating it with a dataset instead of the query. Any suggestions? This is what I have:
DataTable dt = new DataTable("Items");
private void LoadDataGrid()
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Items.ItemID AS #, Items.SerialNo AS 'SERIALNO', Items.Description AS DESCRIPTION, Items.MaxVoltage, Items.FrameSize, Items.ArrivalDate, Items.DepartureDate, Items.Notes, Items.MechType, Items.[Fix-Drawout], CONCAT(Location.Rack, Location.Row, Location.Columnn, Location.Position) AS LOCATION, ItemStatus.Description AS STATUS, Type.Description AS TYPE, Manufacturers.Description AS MANUFACTURERS FROM Items INNER JOIN Location ON Items.LocationID = Location.LocationID INNER JOIN ItemStatus ON Items.Status = ItemStatus.StatusID INNER JOIN Type ON Items.TypeID = Type.TypeID INNER JOIN Manufacturers ON Items.ManufacturerID = Manufacturers.ManufacturerID", AEAcnn))
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
This is the filter expression I'm using (with a combobox)
private void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
dataGridView1.DataSource = dv.ToTable();
}
}
The app crashes when the column TYPE can't be found, even though the name is actually TYPE.
Try something like this:
if (dt.Rows.Count > 0)
{
string str = string.Format("[TYPE] LIKE '%{0}%'", textBox14.Text.Replace("'", "''"));
dt.CaseSensitive = false;
DataTable dt1 = dt.Select(str).CopyToDataTable();
dataGridView1.DataSource = dt1;
}
Despite the unconventional column names, I don't see anything incorrect with the code if you are getting past filling the data table with the adapter, which apparently is the case since you get no error until the keypress event. Since we can't see the entire context of the code I suspect you are not binding the data you think you are, or the binding is changing somewhere else that you haven't noticed.
See this LINQPad script for proof it works:
Form frm = new Form();
DataTable dt = new DataTable("Items");
DataGridView dataGridView1 = new DataGridView();
TextBox textBox14 = new TextBox();
TextBox cmbFilterSearch = new TextBox();
void Main()
{
PopulateDataTable(dt);
BuildForm(frm, dt);
Application.Run(frm);
}
void BuildForm(Form frm, DataTable dt)
{
frm.Height = 500;
frm.Width = 900;
cmbFilterSearch.Text = "TYPE";
frm.Controls.Add(cmbFilterSearch);
textBox14.Text = "filter...";
textBox14.Location = new Point(0,50);
frm.Controls.Add(textBox14);
textBox14.KeyPress += txtFilter_KeyPress;
dataGridView1.DataSource = dt;
dataGridView1.Location = new Point(0, 80);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.Width = 800;
frm.Controls.Add(dataGridView1);
}
void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
Console.WriteLine(dv.RowFilter);
dataGridView1.DataSource = dv.ToTable();
}
}
void PopulateDataTable(DataTable dt)
{
dt.Columns.Add("#", typeof(int));
dt.Columns.Add("'SERIALNO'", typeof(string));
dt.Columns.Add("DESCRIPTION", typeof(string));
dt.Columns.Add("MaxVoltage", typeof(string));
dt.Columns.Add("FrameSize", typeof(string));
dt.Columns.Add("ArrivalDate", typeof(DateTime));
dt.Columns.Add("DepartureDate", typeof(DateTime));
dt.Columns.Add("Notes", typeof(string));
dt.Columns.Add("MechType", typeof(string));
dt.Columns.Add("Fix-Drawout", typeof(string));
dt.Columns.Add("LOCATION", typeof(string));
dt.Columns.Add("STATUS", typeof(string));
dt.Columns.Add("TYPE", typeof(string));
dt.Columns.Add("MANUFACTURERS", typeof(string));
DataRow row = dt.NewRow();
row[0] = 1;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "KEYWORD";
row[12] = "ACME";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 2;
row[1] = "43537953";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Reserved Word";
row[12] = "Conglomico";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 3;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Identifier";
row[12] = "Enormico";
dt.Rows.Add(row);
}
Try it this way.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Filter DataView");
adapter.Dispose();
command.Dispose();
connection.Close();
dv = new DataView(ds.Tables[0], "Product_Price < = 3000", "Product_Name", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
I am currently developing a C# Windows Form Application.
Now I am trying to use a SQL Command to retrieve information from the database to fill in the information that I need to have in my Application.
A sample query would be "select * from Location"
In the Location table there would be variables like locationId, LocationName , districId etc etc.
I used the following code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
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["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
The output is:
but it should be like this:
you have to change some code
private void button1_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
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["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
Added the following code
listView1.View = View.Details;
and it worked.
private void FormView_Load(object sender, EventArgs e)
{
sample = new DataTable(); //Sample Data
sample.Columns.Add("id", typeof(string));
sample.Columns.Add("name", typeof(string));
sample.Rows.Add("1", "apple");
sample.Rows.Add("2", "acer");
sample.Rows.Add("3", "alpha");
sample.Rows.Add("4", "beat");
sample.Rows.Add("5", "ball");
sample.Rows.Add("6", "cat");
sample.Rows.Add("7", "catch");
sample.Rows.Add("10", "zebra");
listViewEx1.View = View.Details;
listViewEx1.Columns.Add("id");
listViewEx1.Columns.Add("name");
}
listViewEx1.Items.Clear();
listViewEx1.FullRowSelect = true;
foreach (DataRow row in sample.Rows)
{
ListViewItem item = new ListViewItem(row["id"].ToString());
item.SubItems.Add(row["name"].ToString());
listViewEx1.Items.Add(item); //Add this row to the ListView
}
this is my code...i just try to search the result by the name of school.but the grid view didnt show any thing.my code is
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
gvResult.DataSource = dtbl;
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
}
protected void Button1_Click(object sender, EventArgs e)
{
gridfill();
}
public DataTable markViewAll()
{
DataTable dtbl = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewAll", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.Fill(dtbl);
return dtbl;
}
public DataTable markViewBySchool(string viewBySchool)
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewBySchool",sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#schoolName", SqlDbType.VarChar).Value = viewBySchool;
sqlda.Fill(dtbClass);
return dtbClass;
}
change as below, there are few problems in your code, why two times databinding to same gridview? even you data bind two times it only show what you set at the last time. i have removed few lines of code and you forgot to call gvResult.DataBind() as well
public void gridfill()
{
markSp spMark = new markSp();
gvResult.DataSource = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataBind();
}
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.Databind(); // You forgot DataBind()
}
Since you have tagged with ASP.Net, you need to call DataBind
gvResult.DataBind();
So your method would be:
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll(); //you are not using this anywhere
gvResult.DataSource = dtbl; // so you can get rid of these two lines
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.DataBind(); // This is missing
}
You should see: ASP.NET data binding overview
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();