I am using the following function to populate my ComboBox
public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName, string AValue, string Adisplay)
{
string Value = AValue;
string display = Adisplay;
using (var CONN = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Test.accdb;"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
MessageBox.Show(e.ToString());
return;
}
DropDownName.DataSource = dt;
DropDownName.ValueMember = Value;
DropDownName.DisplayMember = display;
}
}
And I'm calling it in the load form:
private void Form1_Load(object sender, EventArgs e)
{
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
}
2.After that I'm using the same Function in the event of Selectedindexchanged event to populate another ComboBox:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
And for the population of the two combobox's everything works fine however here is the issue
I have two combobox's as shown in the pic :
So te first combobox ( country ) loaded in the form perfectly
but what I'm trying to do is to make the the second combobox ( the state ) being selected from Database only when I select the country but what happen is that the code runs and the second combobox goes and select from database whatever is the selected index in the first combo is as the pic shows
So what I basically want to do is to make the second Combo being populated only when I select an index from the first combobox.
Put your code in SelectionChangeCommitted Instead of SelectedIndexChanged
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
I think your problem is being cause because the population of the first combo box fires the event to populate the second one. One way around it is to have something like the following in comboBox1_SelectedIndexChanged(object sender, EventArgs e).
if (comboBox1.Text == string.Empty) { return; }
If that doesn't work try using the "SelectedIndex > 0" or "SelectedValue" property.
As a point of note your code is potentially prone to SQL injection attacks, if anyone was able to modify your combo-box items.
You need to identify wether the item is really changed from Combobox or not by using SelectedIndex property.
Try This:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex >= 0)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Change your following method to
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1 && comboBox2.SelectedIndex != -1 )
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Before submitting for query the DB you validate your both comboboxes. Check for any selected item.
Thanks
Srikanth
Remove the SelectedIndexChanged event handler before calling FillDropDownList method, and re-apply it after the ComboBox is populated.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
Related
I am trying to code an accounting system into which I should enter a product id, product name and product price. After that it should be stored in a .accdb file
My problem is when I enter more than 10 digits into product id the datagridview gives me an error saying that the value is too large for int32 type.
Error:
Additional information: Value was either too large or too small for an
Int32.Couldn't store <6221060003181> in Item_Code Column. Expected
type is Int32.
When I open the accdb file, I found the data stored; but next time I open the form, it gives me that error!
public partial class Productentry : MetroFramework.Forms.MetroForm
{
public OleDbConnection connection = new OleDbConnection();
public Productentry()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Sama_Software\WindowsFormsApplication1\WindowsFormsApplication1\DB.accdb;Jet OLEDB:Database Password=**************";
}
private void Productentry_Load(object sender, EventArgs e)
{
ViewData();
// TODO: This line of code loads data into the 'dBDataSet.Product' table. You can move, or remove it, as needed.
this.productTableAdapter1.Fill(this.dBDataSet.Product);
ViewData();
}
void ViewData()
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Product]",connection);
da.Fill(this.dBDataSet.Product);
}
private void bunifuButton4_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuButton3_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("INSERT INTO [Product] (Item_Code, Item_Name, Price) VALUES ('" + Pidn.Text + "','" + name.Text + "','" + price.Text + "')", connection);
da.Fill(dBDataSet)
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void Cat_TextChange(object sender, EventArgs e)
{
}
private void bunifuButton1_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("UPDATE [Product] WHERE [Item_Code]=" + Pidn.Text + " SET [Item_Name]='" + name.Text + "',[Price]=" + price.Text + "", connection);
da.Fill(dBDataSet);
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void bunifuButton4_Click_1(object sender, EventArgs e)
{
this.Close();
}
private void Pid_TextChange(object sender, EventArgs e)
{
}
}
}
Store the barcode as text.
Even though it is build by digits, it is not a number but a code of fixed length, and it may even have a leading zero.
I have a website where the admin can delete or add new gridview. For example, if i currently have gridview for giordano products and wanted to change the brand to bossini products. When the admin clicked edit button, the whole gridview and code for giordano products should be removed and if i'm already in update mode and changed the brand name to "bossini" and clicked update, It should add new gridview and code for bossini products.
Now here's the problem. When i do click the edit button, it will remove the whole gridview code but the gridview itself still appears in the website. I finally know that i need to refresh the page but i don't know the best way yet. I have tried Response.Redirect("urls") in GuitarBrandsGridView_RowEditing, but it is not working and it is giving me an exception. It works for GuitarBrandsGridView_RowDeleting tho. I just assumed that maybe it would work for my edit button but it failed.
My goal is, when i click the edit button in gridview, the whole webpage should refresh and then proceed to update mode. Hope this makes sense.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
bindgridviewguitarbrands();
BindGridViewDataList.GetItemsLoad();
}
}
//Start of Gridview Code for Guitar Brands
private void bindgridviewguitarbrands()
{
con1.Open();
cmd1.CommandText = "SELECT * FROM [guitarBrands]";
cmd1.Connection = con1;
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(ds1);
con1.Close();
GuitarBrandsGridView.DataBind();
}
protected void GuitarBrandsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
Button button = (Button)e.Row.FindControl("GuitarBrandsGridViewBtnDelete");
button.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + name + "' )");
}
}
protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
con1.Open();
cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd1.Connection = con1;
int a = cmd1.ExecuteNonQuery();
con1.Close();
if (a > 0) {
bindgridviewguitarbrands();
}
Response.Redirect("~/Pages/OverviewGuitarData.aspx");
}
protected void GuitarBrandsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GuitarBrandsGridView.EditIndex = e.NewEditIndex;
string id = GuitarBrandsGridView.DataKeys[e.NewEditIndex].Value.ToString();
Label name = (Label)GuitarBrandsGridView.Rows[e.NewEditIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
bindgridviewguitarbrands();
Response.Redirect("~/Pages/OverviewGuitarData.aspx");//this one is not working
}
// row update event
protected void GuitarBrandsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// find student id of edit row
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
// find updated values for update
TextBox type = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtType");
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
TextBox image = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtImage");
cmd1 = new SqlCommand("UPDATE [guitarBrands] SET Type = '" + type.Text + "', Name = '" + name.Text + "', Image = '" + image.Text + "' WHERE ID = " + id, con1);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text, ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
// cancel row edit event
protected void GuitarBrandsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text,ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
you need not refresh whole page
GuitarBrandsGridView.DataSource = ds1
GuitarBrandsGridView.DataBind();
then will update new data
Response.Redirect("http://localhost:14999/Home/Index");
Where you want your page to refresh you need to give full path of the page it will reload that page.
I hope it will work coz its working for me
i am trying to update Gridview by Code behind file.
on clicking the update button i get "Incorrect syntax near the keyword set
The tableName is showing properly
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label l=GridView1.Rows[e.RowIndex].FindControl("ID") as Label;
TextBox question=GridView1.Rows[e.RowIndex].FindControl("questions") as TextBox;
TextBox answer=GridView1.Rows[e.RowIndex].FindControl("answer") as TextBox;
TextBox option1=GridView1.Rows[e.RowIndex].FindControl("op1") as TextBox;
TextBox option2=GridView1.Rows[e.RowIndex].FindControl("op2") as TextBox;
TextBox option3=GridView1.Rows[e.RowIndex].FindControl("op3") as TextBox;
TextBox option4=GridView1.Rows[e.RowIndex].FindControl("op4") as TextBox;
SqlDataSource1.UpdateCommand = "update " + tableName + " set [questions]='" + question.Text + "',[answer]='" + answer.Text + "',[op1]='" + option1.Text + "',[op2]='" + option2.Text+"',[op3]='"+option3.Text+"',[op4]='"+option4.Text+"' where ID="+l.Text;
//GridView1.DataBind();
}
I have initialized tableName variable inside Page_Load event handler
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
According to your comment, here's what your Page_Load method look like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
}
That will make tableName empty when GridView1_RowUpdating is executed, so the value of SqlDataSource1.UpdateCommand will become update set [questions]=... instead of update J2EE_testMaster set [questions]=.... You need to set the tableName value outside of if (!IsPostBack) block:
protected void Page_Load(object sender, EventArgs e)
{
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
tableName = "J2EE_testMaster";
}
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
}
}
}
You also need to parameterize your SQL query to avoid SQL Injection.
This question already has an answer here:
how to update data grid view in winforms?
(1 answer)
Closed 9 years ago.
i have 2 forms and dont know how to update the datagridview, if some can simply guide me please. form1 is as follows:
public partial class frmBooking : Form
{
//instance of sqlConnection created
SqlConnection con = new SqlConnection("Data Source=....");
public frmBooking()
{
InitializeComponent();
//sets the time selecter to a time format and selects the hours and mins only in 24 hour format.
TimeOfBooking.CustomFormat = "HH:mm";
TimeOfBooking.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
//combo box get data from database and updates when new customer is added
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
NameOfCustomer.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT GroupName FROM Customer ORDER BY GroupName ASC", con);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NameOfCustomer.Items.Add(dr["GroupName"]);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//ends here
}
//sets the facility name so its copied from the previous(facility to be booked) form into the Facility text box
public void setFacility(string new_facility)
{
Facility.Text = new_facility;
}
//sets the date so its copied from the previous(facility to be booked) form into the date text box
public void setDate(string new_date)
{
Date.Text = new_date;
}
//adding a new customer button, redirects user to the add customer page
private void btnAddCust_Click(object sender, EventArgs e)
{
frmNewCustomer newCust = new frmNewCustomer();
newCust.Show();
this.Close();
}
//cancel button will redirect the user to the main page
private void btnCancel_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
this.Close();
}
private void frmBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
}
private void lblBookingForm_Click(object sender, EventArgs e)
{
}
private void btnConfirm_Click(object sender, EventArgs e)
{
//validation - if any of the mandotory fields are empty an error message will apear next to the text box
if (Facility.Text == "")
{
//MessageBox.Show("Please enter valid Facility, Date, Name Of Customer, Time Of Booking and Hours");
errorFacility.SetError(Facility, "Enter A Facility To Book");
}
else if (Date.Text == "")
{
errorDate.SetError(Date, "Enter A Valid Date");
}
else if (NameOfCustomer.Text == "")
{
errorCust.SetError(NameOfCustomer, "Enter A Customer To Book");
}
else if (TimeOfBooking.Text == "")
{
errorTime.SetError(TimeOfBooking, "Enter A Time To Book");
}
else if (Hours.Text == "")
{
errorHours.SetError(Hours, "Enter The Hours To Book");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else
{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=...");
//instance of sqlCommand
String query =
"INSERT INTO [Booking] values ('"
+ Facility.Text
+ "', '" + Date.Text
+ "', '" + NameOfCustomer.Text
+ "', '" + TimeOfBooking.Text
+ "', '" + Hours.Text
+ "', '" + Paid.Text
+ "', '" + Notes.Text
+ "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();
MessageBox.Show("Sucessfully Booked");
Form3 mainPage = new Form3();
mainPage.Show();
this.Close();
}
}
}}
this is the form i am using to add a Booking.
The second form i have is the one with the datagridview, which i want to update when the booking is made the code for that is as follows:
public partial class frmViewBookings : Form
{
public frmViewBookings()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Form3 mainpage = new Form3();
mainpage.Show();
this.Close();
}
private void frmViewBookings_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
}
}
To display data on your datagrid you would have to set it's Datasource first which you would do like this
datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView
Whenever you want to refresh it you will just have to fill your tableadapter again and set your gridview's datasource to it.
(Create a seperate method to load datagridview)
I have 2 tables 'contract' and 'customer', they have fk relationship. I drag 'contact' onto form then do so with 'customer', both are details type. The data of 2 tables are shown on form accordingly. The problem is when I modify then click save button only data of 'contract' table is updated.
private void button67_Click(object sender, EventArgs e)
{
if (textBox81.Text == "")
{
MessageBox.Show("you must choose table name");
}
if (textBox81.Text != "")
{
connect();
cmd = new OleDbCommand("select * from " + textBox81.Text + " ", conn);
ds = new DataSet();
dp = new OleDbDataAdapter(cmd);
dp.Fill(ds,""+textBox81.Text+"");
cm = (CurrencyManager)this.BindingContext[ds];
textBox79.DataBindings.Add("text",ds,""+textBox81.Text+""+".ProdS_name");
textBox80.DataBindings.Add("text", ds, "" + textBox81.Text + "" + ".rate");
}
}
private void button58_Click(object sender, EventArgs e)
{
cm.Position++;
}
private void button59_Click(object sender, EventArgs e)
{
cm.Position= cm.Count - 1; ;
}
private void button61_Click(object sender, EventArgs e)
{
cm.Position=0;
}