creating Cascaded dropdowns(WinForm) - c#

I am using below code to fill my combobox ,now usingcode is working and i am getting country combobox with country items,but If I write using code in comboBox1_SelectedIndexChanged than using code doesn't work,why is that so ? and because of this i am not getting state dropdown based on country selected ,how it should be done?
public partial class RegPatient : Form
{
DBHandling db = new DBHandling();
string cmbvalue="";
public RegPatient()
{
InitializeComponent();
using (DataTable dt = DBHandling.GetCountryDataTable())
{
comboBox1.DataSource = new BindingSource(dt, null);
comboBox1.DisplayMember = "CountryName"; //column to show in comboBox
comboBox1.ValueMember = "Code";
}//here the table is disposed
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//using code not working here
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text) )
{
// contine using dt
comboBox2.DataSource = new BindingSource(dt, null);
comboBox2.DisplayMember = "ProvinceName";
}//here the table is disposed
}
}
Code for getting datatable country and state
public static DataTable GetCountryDataTable()
{
DataTable countryTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sonorepo.mdb")) //use your conn. string here
{
using (OleDbDataAdapter da = new OleDbDataAdapter(#"SELECT CountryName, Code FROM Country", con))
da.Fill(countryTable);
}
return countryTable;
}
public static DataTable GetStateDataTable(string countryCode)
{
DataTable stateTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sonorepo.mdb"))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(#"SELECT ProvinceName FROM Province where Country='" + countryCode + "'", con))
da.Fill(stateTable);
}
return stateTable;
}
Thanks in advance

in the method comboBox2_SelectedIndexChanged you cannot create a local DataTable and use it as the datasource. After your code leaves the using statement the DataTable will be destroyed, leaving comboBox2 without a data source.
Leave out the using statement:
DataTable dt = DBHandling.GetStateDataTable(comboBox1.Text)
You are probably just copying a reference to an existing DataTable. So why would you want to dispose it?

Delete the comboBox2_SelectedIndexChanged event and double click on the ComboBox2 to create the event again and check if the event is getting fired.
If its ASP.Net application check if you have set AutoPostBack property

Related

Why Stored Procedure Data from a class doesn't display in Datagridview on my form

I'm trying to transfer this code to a class to avoid messy code in a form / user control. I display the data stored procedure successfully in my datagridview when the code is in my form / user control but when I tried to a class it doesn't work anymore. This is the code I'm working with in my class:
My class:
public class DisplayCustomer
{
public void Display_Customer(DataTable dt, DataGridView dgv)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SalesInventoryManagement.Properties.Settings.Setting"].ConnectionString))
{
using (var cmd = new SqlCommand("usp_GetCustomer", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
using (var sda = new SqlDataAdapter(cmd))
{
dt = new DataTable();
sda.Fill(dt);
// dt.Load(cmd.ExecuteReader());
dgv = new DataGridView { DataSource = dt };
}
con.Close();
}
}
}
}
My user control:
public partial class ManageCustomer : UserControl
{
public ManageCustomer()
{
InitializeComponent();
}
public DataTable dbdataset;
private void ManageCustomer_Load(object sender, EventArgs e)
{
DisplayCustomer dc = new DisplayCustomer();
dc.Display_Customer(dbdataset, CustomersList);
}
}
I think there are two problems,
Use existing Datagridview, instead of create new.
dgv = new DataGridView { DataSource = dt };
try to do :
dgv.DataSource = dt;
Also, if your Datagridview located at UserControl, pass it as
ref
Display_Customer(DataTable dt, ref DataGridView dgv)
So, when you call it
dc.Display_Customer(dbdataset, ref CustomersList);
Let me know if this does not help. I am still on the way to office... So, didn't test the code. :)
try it and update me

Can't get data to display in textbox from a programmatically created datagridview

I am programmatically creating 3 datagridviews depending on what is selected in a listbox.
I am creating them this way because working with a lot of objects on the form is messy and difficult, this is a lot cleaner.
But no matter what type of event I introduce outside of the listBox1_SelectedIndexChanged event, and I have looked at lots of websites and tried a half dozen different ways, I can't get the text box I have created to display text from these datagridviews. (I have been working only with data from gridC so far)
I can't help but feel that the way the grid is being created has something to do with this. Has anyone done this before? I would really prefer to stick with creating them on the fly if possible.
Sorry if I have left out something someone might need to know. Thank you!!
Code:
(I've deleted the contents of the other two if statements):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace MyWiki_8_4_16
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("<Connection String>");
string qryQuery = null;
DataGridView gridC = new DataGridView();
DataGridView gridG = new DataGridView();
DataGridView gridF = new DataGridView();
public Form1()
{
InitializeComponent();
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"select Stuff(table_name, 1, 4, '') as table_name from INFORMATION_SCHEMA.Tables where table_name not like 'Ref%'", conn);
adapter.Fill(ds);
this.listBox1.DataSource = ds.Tables[0];
this.listBox1.DisplayMember = "table_name";
conn.Close();
gridC.Visible = false;
gridC.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string text = listBox1.GetItemText(listBox1.SelectedItem);
string constring = ("Data Source=DSPL7722\\KATMO;Initial Catalog=Physics;Integrated Security=True");
SqlConnection con = new SqlConnection(constring);
if (text == "Categories")
{
con.Open();
qryQuery = ("select Category from tbl_categories");
SqlCommand cmd = new SqlCommand(qryQuery, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
this.Controls.Add(gridC);
gridC.DataSource = dt;
sda.SelectCommand = cmd;
sda.Fill(dt);
gridC.Visible = true;
gridF.Visible = false;
gridG.Visible = false;
gridC.Location = new Point(0, 0);
}
else if (text == "Glossary")
{
}
else if (text == "Formulas")
{
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.gridC.Rows[e.RowIndex];
if (row != null)
txt_Col1.Text = row.Cells["Category"].Value.ToString();
}
}
}//class
}//namespace
Another one:
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in gridC.SelectedCells)
{
cell = selectedCell;
break;
}
if (cell != null)
{
DataGridViewRow row = cell.OwningRow;
txt_Col1.Text = row.Cells["Category"].Value.ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
You are setting the datatable to girdview datasource first and then filling it which is not correct and should be other way round like
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
this.Controls.Add(gridC);
sda.SelectCommand = cmd;
sda.Fill(dt);
gridC.DataSource = dt;
Moreover, looks like at any time you are using only one gridview based on the condition in if block and with that I see it's unnecessary to have 3 gridviews and as well there is no reason why you can't have it declared in design time.
is this what you mean?
you want to pass the text/string value from your datagrid going to your textbox.
try this one
int index = gridC.CurrentRow.Index;
txt_Col1.Text = gridC.Rows[index].Cells["Category"].Value.ToString();

How to print selected row from DataGridView in C# with SQL

Using the following code the first row in SQL is printed only, How can I print selected row from DataGridView in C# with SQL:
public partial class PrintScreen : Form
{
SqlConnection con = new SqlConnection(#"Server = TEST;DataBase=Registration;Integrated Security=true;");
SqlDataAdapter da;
DataTable dt = new DataTable();
public PrintScreen()
{
InitializeComponent();
da = new SqlDataAdapter("select * from data_graduation", con);
da.Fill(dt);
this.dataGridView1.DataSource = dt;
}
private void Print_ys_ar_cert_Click(object sender, EventArgs e)
{
Print_ys_ar_cert frm = new Print_ys_ar_cert();
da = new SqlDataAdapter("select * from data_graduation where ID_gra = '" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'", con);
da.Fill(frm.RegistrationDataSet1.data_graduation);
frm.reportViewer2.RefreshReport();
frm.Show();
}
}
Currently you are passing value of Cells[0] of first row of the grid, you need to pass value of selected row:
if(dataGridView1.SelectedRows.Count>0)
{
var selectedValue = dataGridView1.SelectedRows[0].Cells[0].ToString();
//rest of code
}
Since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report this way:
var row = ((DataRowView)(dataGridView1.SelectedRows[0].DataBoundItem)).Row;
frm.RegistrationDataSet1.data_graduation.Rows.Add(row.ItemArray);
//rest of code

Dynamically update combobox based on user selection

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();
}

C# WPF - Live search in a DataTable

I have a WPF Browserapplication which gets data stored on a SQL Server, stores it in a DataTable and displays it in a DataGrid. Now I want to have a TextBox where you can search entries in the DataTable but when I load the Application I'm getting an error telling me, that the row [Company] cannot be found.
I think the problem is, that the DataTable isn't yet filled when the filter is being applied to the DataTable. Can someone please give me a hint how to make this working?
DataTable dt = new DataTable();
public Page1()
{
InitializeComponent();
showSQLData();
}
private void showSQLData()
{
string sqlConnectionString = #"blabla";
string sqlCommandString = "SELECT * FROM Excel_import";
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
{
SqlCommand cmd = new SqlCommand(sqlCommandString, sqlConnection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridSQLData.ItemsSource = dt.DefaultView;
}
}
private void textBoxSearch_TextChanged(object sender, TextChangedEventArgs e)
{
dt.DefaultView.RowFilter = string.Format("Company LIKE '%{0}%'", textBoxSearch.Text);
}
Based on you latest comment I would guess that textBoxSearch_TextChanged is being fired from within the InitializeComponent() call. You could check that dt.Rows.Count > 0 in textBoxSearch_TextChanged and return if that condition is not met.

Categories

Resources