I've got a combobox which retrieve data from a select and a datagridview which retrieve data from another query. I would like to filter the datagridview using the comboboxvalue. I am trying everything but nothing work. Could you please help? Moreover, why when I declare dataview=((DataTable)datagridview.datasource.defaultview (first row in combobox_SelectedIndexChanged ) I can't see any values in the combobox anymore, instead I see System Data DataRowView but the first question is more important for me
private void Form5_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand(" SELECT id, customername+' - '+cast(inserted as varchar(19)) as targ FROM bf where customername>'a' order by customername asc, inserted desc ", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("targ", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "targ";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT [id],[CustomerName[email],[Capital] FROM baf order by id desc";
var c = new SqlConnection("Data Source=xxxxxx;Initial Catalog=xxxxx;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 = "id = {comboBox1.Text}";
// }
//}
}
You need to properly use BindingSource for the purpose. Below is the complete working example. To experiment with it what you need is as under:
Create a blank form Q1
Add one DataGridView control and one ComboBox control to the form
Copy paste below code into Q1.cs file
Run and experiment
I hope this will get you going nicely.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WinFormQ
{
public partial class Q1 : Form
{
public Q1()
{
InitializeComponent();
}
BindingSource bs;
private void Q1_Load(object sender, EventArgs e)
{
// SqlConnection conn = new SqlConnection(#"Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True;");
// conn.Open();
// SqlCommand sc = new SqlCommand(" SELECT id, customername+' - '+cast(inserted as varchar(19)) as targ FROM bf where customername>'a' order by customername asc, inserted desc ", conn);
// SqlDataReader reader;
//
// reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("targ", typeof(string));
// dt.Load(reader);
dt.Rows.Add("1", "Targ-1"); // example code - remove
dt.Rows.Add("2", "Targ-2"); // example code - remove
dt.Rows.Add("3", "Targ-3"); // example code - remove
dt.Rows.Add("4", "Targ-4"); // example code - remove
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "targ";
comboBox1.DataSource = dt;
// var select = "SELECT [id],[CustomerName[email],[Capital] FROM baf order by id desc";
// var c = new SqlConnection("Data Source=xxxxxx;Initial Catalog=xxxxx;Integrated Security=True;"); Your Connection String here
// var dataAdapter = new SqlDataAdapter(select, c);
// var commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
DataTable bf = new DataTable("BF");
bf.Columns.Add("id", typeof(string)); // example code - remove
bf.Columns.Add("CustomerName", typeof(string)); // example code - remove
bf.Columns.Add("Email", typeof(string)); // example code - remove
bf.Columns.Add("Capital", typeof(string)); // example code - remove
ds.Tables.Add(bf);
bs = new BindingSource(ds, "BF");
// dataAdapter.Fill(bf);
bf.Rows.Add("1", "Customer-1", "Email-1", "Capital-1"); // example code - remove
bf.Rows.Add("1", "Customer-2", "Email-2", "Capital-1"); // example code - remove
bf.Rows.Add("2", "Customer-3", "Email-3", "Capital-2"); // example code - remove
bf.Rows.Add("3", "Customer-4", "Email-4", "Capital-3"); // example code - remove
bf.Rows.Add("3", "Customer-5", "Email-5", "Capital-3"); // example code - remove
bf.Rows.Add("3", "Customer-6", "Email-6", "Capital-3"); // example code - remove
bf.Rows.Add("4", "Customer-7", "Email-7", "Capital-4"); // example code - remove
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bs;
this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "Remove filter")
{
bs.RemoveFilter();
}
else if (comboBox1.SelectedValue == null)
{
bs.RemoveFilter();
}
else
{
bs.Filter = "id = " + comboBox1.SelectedValue;
}
}
}
}
I resolved in this way (maybe not the most elegant but it does work):
private void Form5_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand(" SELECT id, customername+' - '+cast(inserted as varchar(19)) as targ FROM baf where customername>'a' order by customername asc, inserted desc ", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("targ", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "targ";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT [id],[CustomerName], [email],[CapActual] FROM baf order by id desc";
var c = new SqlConnection("Data Source=xxxx;Initial Catalog=xxxxx;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
var bf = new DataTable("BF");
ds.Tables.Add(bf);
dataAdapter.Fill(bf);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bf;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var select = "SELECT [id],[CustomerName],[email],[CapActual] FROM baf where id="+comboBox1.SelectedValue+" order by id desc";
var c = new SqlConnection("Data Source=xxxxx;Initial Catalog=xxxxxx;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select,c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
var bf = new DataTable("BF");
ds.Tables.Add(bf);
dataAdapter.Fill(bf);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bf;
}
}
}
For the viewers who are interested in finding how to make the code in question work successfully, I present the solution below. To achieve readiness to experiment, the data is hard coded which need be modified as per actual situation.
DataView dataView = null; // <<< Difference #1
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("targ", typeof(string));
dt.Rows.Add("1", "Targ-1"); // example code - remove
dt.Rows.Add("2", "Targ-2"); // example code - remove
dt.Rows.Add("3", "Targ-3"); // example code - remove
dt.Rows.Add("4", "Targ-4"); // example code - remove
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "targ";
comboBox1.DataSource = dt;
var bf = new DataTable("BF");
bf.Columns.Add("id", typeof(string)); // example code - remove
bf.Columns.Add("CustomerName", typeof(string)); // example code - remove
bf.Columns.Add("Email", typeof(string)); // example code - remove
bf.Columns.Add("Capital", typeof(string)); // example code - remove
bf.Rows.Add("1", "Customer-1", "Email-1", "Capital-1"); // example code - remove
bf.Rows.Add("1", "Customer-2", "Email-2", "Capital-1"); // example code - remove
bf.Rows.Add("2", "Customer-3", "Email-3", "Capital-2"); // example code - remove
bf.Rows.Add("3", "Customer-4", "Email-4", "Capital-3"); // example code - remove
bf.Rows.Add("3", "Customer-5", "Email-5", "Capital-3"); // example code - remove
bf.Rows.Add("3", "Customer-6", "Email-6", "Capital-3"); // example code - remove
bf.Rows.Add("4", "Customer-7", "Email-7", "Capital-4"); // example code - remove
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bf;
dataView = bf.DefaultView; // <<< Difference #2
this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged); // <<< Difference #3
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = string.Format("id = '{0}'", comboBox1.SelectedValue); // <<< Difference #4
}
}
Related
I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}
How to Pass data table from DataGridView ro ReportViewer ?
in a win Form I have a DataGridView control that fills from a SqlDataAdapter , and I added a check box column to it. for "ready to print"(or smt like this)
now I want to create a report with ReportViewr to show only checked rows in my DataGridView.
here is codes of my form1 (Contains datagridview)
private void Fill_DGV_Sefaresh()
{
try
{
MyDB db = new MyDB();//class that contains my SQL Connection
string sql = "SELECT sid, CONVERT(VARCHAR(10), cast(sdate as date), 111)sdate, sdes, sfor, suname, isdone, sqty FROM sefaresh order by sid desc";
SqlDataAdapter sda = new SqlDataAdapter(sql,db.MyConn);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
sda.Fill(ds);
bs.DataSource = ds.Tables[0].DefaultView;
bindingNavigator1.BindingSource = bs;
dataGridView1.DataSource = bs;
}
catch { }
}
codes of my form2 (contains ReportViewer Control)
private SqlDataAdapter idata()
{
MyDB db = new MyDB();
string sql = "SELECT * FROM sefaresh";
SqlDataAdapter sda = new SqlDataAdapter(sql, db.MyConn);
return sda;
}
private void SefareshView_Load(object sender, EventArgs e)
{
idata().Fill(this.DS_Sefaresh.sefaresh);//DS_Sefaresh is a dataset item , sefaresh is a Table adapter
this.reportViewer1.RefreshReport();
}
Try something like the following,
ReportDataSource Rds = new ReportDataSource(dataSetName, bs);
reportViewer1.LocalReport.DataSources.Add(Rds);
Where bs is your BindingSource, dataSetName is the name of the dataset in the report, Rds is the datasource for the ReportViewer, and reportViewer1 is the ReportViewerControl.
If you for some reason need to take the data directly from the DataGridView just replace bs with dataGridView1.DataSource.
Segue
private void tbcaixas_Leave(object sender, EventArgs e)
{
Carga();
int caixas = Convert.ToInt32(tbcaixas.Text);
List<int> lista = new List<int>();
for (int i = 1; i <= caixas; i++)
{
DataRow linha = dt.NewRow();
linha["ncaixa"] = "1/" + i;
linha["loja"] = tbLoja.Text.ToUpper();
dt.Rows.Add(linha);
}
}
private void Carga()
{
dt = new DataTable();
dt.Columns.Add("ncaixa", typeof(string));
dt.Columns.Add("artigo", typeof(string));
dt.Columns.Add("tam", typeof(string));
dt.Columns.Add("cor", typeof(string));
dt.Columns.Add("arte", typeof(string));
dt.Columns.Add("qtd", typeof(string));
dt.Columns.Add("und", typeof(string));
dt.Columns.Add("loja", typeof(string));
dgvDados.DataSource = dt;
}
private void btnImprimir_Click(object sender, EventArgs e)
{
DataTable dtImpressao = ((DataTable)dgvDados.DataSource);
var parametro1 = new ReportParameter("data", dtpData.Text);
var parametro2 = new ReportParameter("cliente", tbCliente.Text);
var parametro3 = new ReportParameter("notafiscal", tbNotaFiscal.Text);
var parametro4 = new ReportParameter("pesobruto", tbPesoBruto.Text);
var parametro5 = new ReportParameter("pesoliquidado", tbPesoLiquidado.Text);
var parametro6 = new ReportParameter("pesoliquidado", cbEmpresa.SelectedItem.ToString());
ReportParameter[] paremetros = new ReportParameter[] { parametro1, parametro2, parametro3, parametro4, parametro5 };
ImpressaoHelper.Imprimir(null, "DataSetRelatorios", "br.com.bonor.Core.relatorios.pcp.Romaneio.rdlc", dtImpressao);
}
}
}
I have a DevExpress GridView with EditingMode = EditFormInplace.
I try to update GridView with multiple tables and get error
Dynamic SQL generation is not supported against multiple base tables
I think, it is nessesary to add UpdateCommand to the dataAdapter. But I don't understand how to get the parameters values for the Update query (from edited row).
What is the correct way to update DataSource with multiple (joined) tables?
Code:
public Form2()
{
InitializeComponent();
dataAdapter = new SqlDataAdapter("select t.Id, t.DT, t.Name, t.Age, l.SecondName from TestTime t left join TestTimeLinked l on l.Id = t.Id", Properties.Settings.Default.MARKETConnectionString);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
gridControl1.DataSource = bindingSource1;
}
private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MARKETConnectionString))
{
conn.Open();
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
}
DataRow r = gridView1.GetDataRow(e.RowHandle); to get edited row values.
And completely method code:
private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
{
DataRow r = gridView1.GetDataRow(e.RowHandle);
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MARKETConnectionString))
{
conn.Open();
dataAdapter.UpdateCommand = conn.CreateCommand();
dataAdapter.UpdateCommand.CommandText = "UPDATE TestTimeLinked set SecondName = #Name where Id = #Id";
dataAdapter.UpdateCommand.Parameters.AddWithValue("Name", r.Field<string>("SecondName"));
dataAdapter.UpdateCommand.Parameters.AddWithValue("Id", r.Field<int>("ID"));
dataAdapter.UpdateCommand.ExecuteNonQuery();
}
}
I need to populate grid based on dropdownlist selected value: my c# coding is
protected void atddroplist_SelectedIndexChanged(object sender, EventArgs e)
{
empatdListBI c = new empatdListBI();
DbConnection b = new DbConnection();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
if (atddroplist.SelectedIndex == 1)
{
b.OpenConnection();
dt = c.LoadRecords(empText.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
b.CloseConnection();
}
}
With this coding Iam unable to see Grid in output. Please help me out
We can check few things
- AutoPostBack of dropdown is set to True
- We are getting data in dt
- If necessary we can put grid in the updatepanel on your page
if (atddroplist.SelectedIndex == 1)
{
empatdListBI c = new empatdListBI();
DbConnection b = new DbConnection();
SqlDataAdapter da = new SqlDataAdapter();
DataTable DT = new DataTable();
DT = c.LoadRecords(empText.Text);
b.OpenConnection();
if (DT.Rows.Count == 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "PopUp", "alert(' Record Not Found...');", true);
txtsearchrecord.Text = "";
txtsearchrecord.Focus();
}
else
{
GridView1.DataSource = DT;
GridView1.DataBind();
}
b.CloseConnection();
}
I am not sure how postback works on WinForms, but I want to allow the ComboBox to update based on the user selection.
Currently when I change the selection of my first ComboBox, it doesn't change the items in the second dropdown. (only showing the first item by default)
In what ways can O alter this?
Code to what I have:
public ContentUploader()
{
InitializeComponent();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... re.OverallID = 1", conString))
{
DataTable dt = new DataTable();
sda.Fill(dt);
sections_drp.ValueMember = "ID";
sections_drp.DisplayMember = "DisplayName";
sections_drp.DataSource = dt;
}
}
sections_drp.SelectedIndexChanged += (o, e) => FillFirstChildren();
}
public void FillFirstChildren()
{
firstChild_drp.Items.Add("Select Item");
firstChild_drp.SelectedIndex = 0;
string sectionId = sections_drp.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... em.ItemID = ("+ sectionId +")", conString))
{
DataTable dt = new DataTable();
sda.Fill(dt);
firstChild_drp.ValueMember = "ID";
firstChild_drp.DisplayMember = "DisplayName";
firstChild_drp.DataSource = dt;
}
}
FillSecondChildren();
}
Winforms does not contain a post back. You will need to tie to the SelectedIndexChanged (or Item or Value) event to filter your second dropdown.
Example:
public void FillFirstChildren()
{
//Your Fill Logic Here
...
//Call FillSecondChildren on selection change
firstChild_drop.SelectedIndexChanged += (o, e) => FillSecondChildren();
}