ive hit a brick wall on what to do next to populate a combobox from a data set currently i have. my database is call "PID2db.mdb" and the table is called "Customer"
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
try {
conn.Open();
string strSql = "Select forename,surname from customer where [customerID] ='" + txtName.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
cboName.DataSource = ds.Tables[0];
cboName.DisplayMember = "forename";
cboName.ValueMember = "surname";
}
finally {
conn.Close();
}
}
any help is appreciated, thanks
edit: added new code segments
Assuming you have a Form with:
Combobox named cboName
TextBox named txtName
Try this :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadCustomerOnCombo();
}
private void LoadCustomerOnCombo()
{
string strCon = Settings.Default.PID2dbConnectionString;
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT forename &\" \" & surname AS FullName, surname FROM customer"; //WHERE [customerID] ='" + txtName.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
cboName.DataSource = ds.Tables[0];
cboName.DisplayMember = "FullName";
cboName.ValueMember = "surname";
}
}
catch (Exception ex)
{
txtName.Text = ex.Message;
Console.WriteLine(ex.Message);
}
}
}
If worked so please tell me how is the where, left commented at the moment, else there are any errors, you'll see inside the textbox.
You need to create a new DataSet, fill it with Data and finally set the ComboBox's DataSource, DisplayMember and ValueMember properties. Here is the code:
using System.Data.OleDb;
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
try {
conn.Open();
string strSql = "Select forename,surname from customer where customer id ='" + txtName.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "forename";
comboBox1.ValueMember = "surname";
}
finally {
conn.Close();
}
Related
I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database
I'm trying to make a button to load and filter my ReportViewer by name but the output is data source instance not supplied. Here is my code:
private void btnReport_Click(object sender, EventArgs e)
{
String sql = "Select * from practise Where name ='" + textBox1.Text + "'";
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
adp.Fill(ds);
ReportDataSource rds = new ReportDataSource("practise", ds.Tables[0]);
reportViewer2.ProcessingMode = ProcessingMode.Local;
reportViewer2.LocalReport.ReportPath = "Report1.rdlc";
if (ds.Tables[0].Rows.Count > 0)
{
reportViewer2.LocalReport.DataSources.Clear();
reportViewer2.LocalReport.DataSources.Add(rds);
reportViewer2.RefreshReport();
}
This could be simple. Please check that your dataset name in the report is not "DataSet1" by default. Also, make sure that the path for report is correct. Here is a working example:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DemoDB"].ConnectionString))
{
String sql = "Select * from practise Where name ='" + textBox1.Text + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
adp.Fill(ds);
ReportDataSource rds = new ReportDataSource("DataSet1", ds.Tables[0]);
reportViewer2.ProcessingMode = ProcessingMode.Local;
reportViewer2.LocalReport.ReportPath = "Report1.rdlc";
if (ds.Tables[0].Rows.Count > 0)
{
reportViewer2.LocalReport.DataSources.Clear();
reportViewer2.LocalReport.DataSources.Add(rds);
reportViewer2.RefreshReport();
}
}
I hope that would help someone.
I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
I'm trying to initialize a DataGridView object. All I did was add the object to my screen without changing any properties. I have code that is run when the user selects the panel it is on. The code looks like this...
DataTable tbl = new DataTable();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand(query, connect);
connect.Open();
try
{
SqlDataAdapter dAdapt = new SqlDataAdapter(cmd);
dAdapt.Fill(tbl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
connect.Close();
dataGridView1.DataSource = tbl;
So is there any other code I have to add or properties I have to set to see the data appear on the grid? Thanks for the help.
Can you try using this code:
void FillData()
{
using (SqlConnection c = new SqlConnection(
#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True"))
{
c.Open();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
using (SqlDataAdapter a = new SqlDataAdapter(
query , c))
{
DataTable tbl = new DataTable();
a.Fill(tbl);
dataGridView1.DataSource = tbl;
}
}
}
To put it into short story
i wanted something like "SELECT companyName FROM table where mainCategory = firstcombobox and subcategory = secondcombobox" , how do i do the sql query?
==========================
Long story
I have created a form , with a working coding , but i need an extra assistance.
Somewhat , i am stuck on trying to figure out how to let the 3rd combobox value , determined by the first and second.
and what i wanted is , something like , getting the value of Main Category and Sub category to effect the list of the third combo box.
i just need the SQL query , such as : "SELECT companyName FROM table where maincategory = firstcombobox and subcategory = secondcombobox"
and then shows the company name within the picks of main and sub category.
Like this :
For the Main Category and Sub-Category , i have it working with this code.
This code also includes the 3rd ComboBox code which right now operates without the first and second combobox attached to the 3rd combobox code.
public partial class User : Form
{
Dictionary<string, List<string>> Category = new Dictionary<string, List<string>>();
DataSet ds1;
public User()
{
InitializeComponent();
}
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");
DataTable dt = ds1.Tables["MAINCATE"];
foreach (DataRow dr in dt.Rows)
{
List<string> SubCats = new List<string>
{
dr["Subcat1"].ToString(),
dr["Subcat2"].ToString(),
dr["Subcat3"].ToString(),
dr["Subcat4"].ToString()
};
Category.Add(dr["mainCate"].ToString(), SubCats);
mainCatU.Items.Add(dr["mainCate"].ToString());
}
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
//**Code for third combobox**
SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
DataTable dt1 = new DataTable();
ListU.DataSource = dt1;
daSearch.Fill(dt1);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
//**----------------------**
conn.Close();
}
private void mainCatU_SelectedIndexChanged(object sender, EventArgs e)
{
if(Category.ContainsKey(mainCatU.SelectedItem.ToString()))
{
subCatU.DataSource = Category[mainCatU.SelectedItem.ToString()];
}
}
and the databases are as shown :
dbo.MAINCATE
dbo.ComDet
and the code for the View Selected Company button is :
private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = #cName", conn);
daS.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dts3 = new DataTable();
daS.Fill(dts3);
dataGridView1.DataSource = dts3.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
conn.Close();
}
again , right now the third combo box is coded to run without the maincategory and subcategory
========================
Answered - Created a button called search , and took the coding from form load into the button , added with SQLCon , and added the SQLQuery needed..
Thx guys.. :)
private void button2_Click_1(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
string myRequest = "SELECT cName FROM ComDet where mainCate = '" + mainCatU.SelectedItem.ToString() + "' and Subcat = '" + subCatU.SelectedItem.ToString() + "'";
SqlDataAdapter daSearch = new SqlDataAdapter(myRequest, conn);
DataTable dtSea = new DataTable();
ListU.DataSource = dtSea;
daSearch.Fill(dtSea);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}
Try calling following function on SelectedValue change event of mainCatU and subCatU combo:
private void SetCompanyList()
{
if (string.IsNullOrEmpty(Convert.ToString(mainCatU.SelectedValue)) || string.IsNullOrEmpty(Convert.ToString(subCatU.SelectedValue))) return;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daMain = new SqlDataAdapter("SELECT cName FROM ComDet where mainCate = #mainCat subCat = #subCate", conn);
daMain.SelectCommand.Parameters.Add("#mainCat", SqlDbType.VarChar).Value = mainCatU.SelectedValue;
daMain.SelectCommand.Parameters.Add("#subCate", SqlDbType.VarChar).Value = subCatU.SelectedValue;
DataTable _table = new DataTable();
daMain.Fill(_table);
ListU.DataSource = _table;
}
you have to use by the following query:
SELECT companyName FROM table where mainCategory = '" + mainCatU.selectedValue + "' and subcategory = '" + subCatU.selectedValue + "'"