I am trying to Fill Combobox2 on combobox1 selectedText changed from the same table in windows form application. I am using sql serevr 2008 database. I am unable to fill combobox2 on combobox selected text changed.
Here is what i have tried:
private void Purchase_Load(object sender, EventArgs e)
{
fillName();
comboBoxName.SelectedIndex = -1;
}
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxName.SelectedText != "")
{
fillMake();
}
}
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
private void fillMake()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Make from Item Where Item_Name='" + comboBoxName.SelectedText + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Make";
comboBoxName.ValueMember = "Item_Name";
comboBoxName.SelectedIndex = -1;
comboBoxName.Text = "Select";
}
Sql server table for Items
Item_Code Item_Name Item_Make Item_Price UnitofMeasurement
Cable anchor 45.0000 meter
Cable polycab 30.0000 meter
Button anchor 15.0000 unit
Button havells 20.0000 unit
Switch cona 70.0000 unit
I have searched for solution but was unfortunate.
please help me out.
Thanks in advance.
It's a little difficult to figure out what you're trying to do, but it sounds like you are trying to populate a second combo box (comboBoxMake?) depending on what is selected in comboBoxName. I am basing this answer on that assumption. Apologies if I have this wrong.
There are lot of things that need attention in this code. Let's look at fillName() first.
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
You need to Dispose() your database objects. This can be accomplished pretty cleanly with using { .. } blocks.
You don't need to manually open the connection; filling the table with the data adapter
does this automatically.
You don't need the call to ExecuteNonQuery().
You should use the SqlDataAdapter constructor overload that takes a command object, since you have already manually created the command.
Finally, based on my assumption of your goal I have added a distinct to your query so it only gets the unique Item_Names.
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
On to fillMake(). The same suggestions apply that I noted above. Additionally:
Parameterize your SQL. Parameterize your SQL. Not only is this far, far safer than concatenating your SQL together, it is much cleaner. Seriously, read about SQL injection: http://en.wikipedia.org/wiki/SQL_injection
The fillMake() method in your original post seems to be repopulating comboBoxName. Is this correct? You mention two combo boxes but your code only references one. I am assuming you mean to populate another combo box (comboBoxMake?) here:
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name = #item_name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#item_name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.DisplayMember = "Item_Make";
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.SelectedIndex = -1;
comboBoxMake.Text = "Select";
}
}
}
}
Lastly, change the code in the event handler so it looks at the Text rather than the SelectedText property:
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text)) // Text instead of SelectedText
{
fillMake();
}
}
Related
What i am trying to do is when a user selects a company from a comboBox then clicks the button the different text boxes are supposed to show the different data from the database.
This is what i have but it doesnt seem to work.
Any suggestions?
private void Edit_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
}
}
private void button3_Click(object sender, EventArgs e)
{
String company = comboBox1.SelectedItem.ToString();
String check = #"SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection(str))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = company;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = (reader["Name"].ToString());
textBox2.Text = (reader["PhNo"].ToString());
textBox3.Text = (reader["Email"].ToString());
textBox4.Text = (reader["Acc"].ToString());
textBox5.Text = (reader["Address"].ToString());
textBox6.Text = (reader["Suburb"].ToString());
textBox7.Text = (reader["PostCode"].ToString());
textBox8.Text = (reader["State"].ToString());
}
}
}
Update: the output of comboBox1.SelectedItem.ToString(); is System.Data.DataRowView so it seems to not be registering what the selected item is. How do i resolve this?
When the DataSource of your combo box is a DataTable, then the object in SelectedItem is of type DataRowView.
So to get a field, you can cast selected item to DataRowView and extract the field value this way:
var name = ((DataRowView)comboBox1.SelectedItem)["Name"].ToString();
In fact ((DataRowView)comboBox1.SelectedItem)["FieldName"] is of type object and you should cast the field to the desired type.
Try this
String check = "SELECT * FROM Companies WHERE Name=#name";
using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=ABCD;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(check, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = comboBox1.SelectedItem.ToString();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["Name"].ToString();
textBox2.Text = reader["PhNo"].ToString();
textBox3.Text = reader["Email"].ToString();
textBox4.Text = reader["Acc"].ToString();
textBox5.Text = reader["Address"].ToString();
textBox6.Text = reader["Suburb"].ToString();
textBox7.Text = reader["PostCode"].ToString();
textBox8.Text = reader["State"].ToString();
}
}
Make sure your connectionstring is proper. Also Have you checked value of comboBox1.SelectedItem.ToString() and same is present in db?
If you are populating drop down from database then refer this: System.Data.DataRowView in DropDownList
Updated:
private void ComboBoxBinding()
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT Name,Id FROM Companies", con);
DataTable dt = new DataTable();
adapt.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = dt;
comboBox1.DataBind();
}
}
You can call this function either in page load or in class constructor.
Try the code below it will work,the thing that you are missing is you are not setting the ValueMember property of your combo box.
Suggestion :
1.Debug your code and make sure that your query is correct and your able to getting the value right values from data source.
2.Make sure that your columns names in your database table are exactly same as you are setting in your combo box display member and value member
using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=\"Student Extended\";Integrated Security=True"))
{
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandText = "SELECT DepartmentId,DepartmentName FROM dbo.TblDepartment"
};
SqlDataAdapter adpater = new SqlDataAdapter(command);
DataTable table = new DataTable();
adpater.Fill(table);
if (txtStdDeptName != null)
{
txtStdDeptName.DataSource = table;
txtStdDeptName.DisplayMember = "DepartmentName";
txtStdDeptName.ValueMember = "DepartmentId";
}
}
Now this may be a "Noob" question. But I cant seem to do any commands that people seem to do with The DataGrid. What is the difference, and why can I only get DataGrid?
My problem is that I am trying to delete rows in the datagrid when they are pulled from a database. But, I cant figure out how because the SelectRows command does not work.
That is what i have so far. Is there anyway i can get DataGrid?
EDIT:
This is how I get information into the datagrid.
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (DataGridViewRow row in userDataGrid.SelectedRows)
{
if (!row.IsNewRow)
dataGridView1.Rows.Remove(row);
}
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=----; Database=----; User id=vsd; password=----";
conn.Open();
dt = new DataTable();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(dt);
userDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
Also, If there is a better way to do this, please let me know as well. I am very new to all of this.
Use the same instance of DataTable every time when you pull rows from db.
DataTable mDataTable = new DataTable(); //class field
public Constructor()
{
InitializeComponent();
userDataGrid.ItemsSource = mDataTable .mDataTable;
}
void PullData()
{
mDataTable.Clear();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(mDataTable );
}
}
It should solve your problem, but it's bad approach.
As Bizz adviced look at MVVM pattern & entity framework.
This is what I ended up doing for deleting the button. Most answers were trying to answer to a DataGridView. But, This is not WinForms or a DataGridView. This is WPF and its just DataGrid.
This is what I did to delete the row from the grid and the database.
private void delete_Click(object sender, RoutedEventArgs e)
{
DataGrid dg = this.aSSIGNMENTDataGrid;
var id1 = (DataRowView)dg.SelectedItem; //Get specific ID From DataGrid after click on Delete Button.
PK_ID = Convert.ToInt32(id1.Row["AssignmentID"].ToString());
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "delete from ASSIGNMENT where AssignmentID='" + PK_ID + "' ";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
filldatagrid();
}
private void filldatagrid()
{
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "select * from ASSIGNMENT";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
aSSIGNMENTDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'
Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.