Running the following code, I find that SelectedIndexChanged method runs before load method... How can I correct this? I tried resetting the events but that didn't work either
namespace adotestquestion
{
public partial class Bill : Form
{
public Bill()
{
InitializeComponent();
}
string constring = "data source=NISHANT-PC ; initial catalog=NIK_DATABASE ; user id=xxxxxx ; password=xxxxxx";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter adapter;
DataSet ds;
DataTable dt;
int qty, tax, total, price;
private void Bill_Load(object sender, EventArgs e)
{
con = new SqlConnection(constring);
cmd = new SqlCommand("select billid from bill", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "billid";
comboBox1.ValueMember = "billid";
MessageBox.Show(id.ToString());
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(comboBox1.Text);
int id;
id = Convert.ToInt32(comboBox1.Text);
con = new SqlConnection(constring);
cmd = new SqlCommand("select * from bill where billid=#id", con);
// cmd.Parameters.Add("#id", Convert.ToInt32(comboBox1.Text));
cmd.Parameters.Add("#id", id);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
textBox1.Text = dr[1].ToString();
textBox2.Text = dr[2].ToString();
textBox3.Text = dr[4].ToString();
textBox4.Text = dr[3].ToString();
textBox5.Text = dr[5].ToString();
textBox6.Text = dr[6].ToString();
textBox7.Text = dr[7].ToString();
textBox8.Text = dr[8].ToString();
textBox9.Text = dr[9].ToString();
textBox10.Text = dr[10].ToString();
}
}
}
}
Unwire the events subscription in InitializeComponent method and wire it at the end of Form_Load.
Instead of trying to change the events, etc. you can simply check if there is anything in fact selected in the combo box in your event. This will keep the code simple and will work correctly.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex >= 0)
{
// your existing code goes here
}
}
A third alternative is to create a private class-level variable like isFormLoading and set it to true initially, then set it to false at the end of your Bill_Load event.
You can check the value of the variable in comboBox1_SelectedIndexChanged and anywhere else it's needed to determine whether a block of code should run or not.
But really, any of the other provided answers will work.
Problem : whenever you bind an Items to your Combobox , SelectedIndexChanged event will be fired.
Solution : inside the SelectedIndexChanged event you need to identify wether it is fired from the Load event or due to the Item selection change.
you can declare a boolean variable ,set it to true whenever control enters into Load event.
from selectedIndexChanged event only execute the code when boolean variable is false.
Note : at the end of the Load event again change the boolean variable to false so that SelectionChanged event will be fired when actually selection Changes in the ComboBox.
Try This:
bool loadevent = false;
private void Bill_Load(object sender, EventArgs e)
{
loadevent = true;
con = new SqlConnection(constring);
cmd = new SqlCommand("select billid from bill", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "billid";
comboBox1.ValueMember = "billid";
MessageBox.Show(id.ToString());
loadevent = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!loadevent)
{
MessageBox.Show(comboBox1.Text);
int id;
id = Convert.ToInt32(comboBox1.Text);
con = new SqlConnection(constring);
cmd = new SqlCommand("select * from bill where billid=#id", con);
// cmd.Parameters.Add("#id", Convert.ToInt32(comboBox1.Text));
cmd.Parameters.Add("#id", id);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
textBox1.Text = dr[1].ToString();
textBox2.Text = dr[2].ToString();
textBox3.Text = dr[4].ToString();
textBox4.Text = dr[3].ToString();
textBox5.Text = dr[5].ToString();
textBox6.Text = dr[6].ToString();
textBox7.Text = dr[7].ToString();
textBox8.Text = dr[8].ToString();
textBox9.Text = dr[9].ToString();
textBox10.Text = dr[10].ToString();
}
}
}
Related
I have created 2 DropDownLists First dropdown contains "TeamName" and second one contain "TeamMember" name. The requirement is when we select particular TeamName from dropdown second dropdown should automatic populates the team member name and after button click data should be inserted in database,It works fine for first button click but second time on the same page "TeamName" dropdown does not show name of department,suddenly it gets lost.So Please suggest me what I need to do to resolve this issue??
Following is the code which I did to achieve this task
User.aspx page code:
User.aspx.cs page code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTeamName();
txtCurrentDate.Text = DateTime.Now.ToString("MM-dd-yyyy");
txtCurrentDate.ForeColor = System.Drawing.Color.Green;
}
}
private void BindTeamName()
{
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamName", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl1.DataSource = ds;
ddl1.DataTextField = "TeamName";
ddl1.DataValueField = "TeamId";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
int TeamId = Convert.ToInt32(ddl1.SelectedValue);
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamResource where TeamId=" + TeamId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl2.DataSource = ds;
ddl2.DataTextField = "EmpName";
ddl2.DataValueField = "EmpId";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(SqlString))
{
SqlCommand cmd = new SqlCommand("InsertUserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#WorkDate", txtCurrentDate.Text);
cmd.Parameters.AddWithValue("#TeamName", ddl1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#TeamMember", ddl2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AvailableBandwidth", ddlAvailable.SelectedItem.Value);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
}
}
I would re-bind the "TeamName" dropdown list after a successful save.
//btnSubmit_Click
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
BindTeamName(); //re-bind the initial dropdown so you can select a new team
}
Actually you can use that method either way, depending on what ClearFields() does.
Is there a way to display data from the database into the textbox but every time you click NEXT new row displays. I have this code but it doesn't work like I want it to because it displays all data into a textbox and not one row at a time.
private void buttonNEXT_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection("data source = people.sqlite");
conn.Open();
SQLiteCommand com = new SQLiteCommand(conn);
com.CommandText = "SELECT id, name, surname FROM people;";
SQLiteDataReader reader = com.ExecuteReader();
while (reader.Read())
{
textBox1.Text += reader["id"].ToString();
textBox2.Text += reader["name"].ToString();
textBox3.Text += reader["surname"].ToString();
}
conn.Close();
}
If you want to have a Next and Previous button and don't want to use a BindingNavigator control on your form, you can use a DataSet to store data and an SQLiteDataAdapter to fill it.
So you can have a function to fill and return a data set:
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SQLiteConnectionconn = new SQLiteConnection(ConnectionString);
SQLiteDataAdapter da = new SQLiteDataAdapter ();
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}
Then you should keep its returns value to a global variable in your main function like FormLoad :
dataset ds; // global variable
int index = 0; // for loop over dataset
private void frm_Load(object sender, EventArgs e)
{
ds = GetDataSet("data source = people.sqlite","SELECT id, name, surname FROM people;");
}
And in your button click:
private void buttonNEXT_Click(object sender, EventArgs e)
{
textBox1.Text = ds.Tables["People"].Rows[i]["id"].ToString();
textBox2.Text = ds.Tables["People"].Rows[i]["name"].ToString();
textBox3.Text = ds.Tables["People"].Rows[i]["surname"].ToString();
i++;
}
Note: You should check for i variable value by each click, it should not be bigger than ds.Tables["People"].Rows.Count
Do the same for previous button if you want it also.
This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}
i'm creating a system that has an add-edit-delete function but whenever i try to edit a value from my ms sql server 2005 it keeps on telling me "cannot find table 0". below is my code i'm using visual studio c# 2008:
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter dad = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(dad);
dad.UpdateCommand = new SqlCommand("UPDATE tblSchools SET Number = #id, School_Name = #school, Province = #prov, City = #city, Brgy = #brgy, Lot_Num = #lot, Area = #area, Mem_Date_Rec = #date, Cenro = #cenro", conn);
dad.UpdateCommand.Parameters.Add("#school", SqlDbType.VarChar).Value = textBox1.Text;
dad.UpdateCommand.Parameters.Add("#prov", SqlDbType.VarChar).Value = comboBox1.Text;
dad.UpdateCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox2.Text;
dad.UpdateCommand.Parameters.Add("#brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.UpdateCommand.Parameters.Add("#lot", SqlDbType.NVarChar).Value = textBox5.Text;
dad.UpdateCommand.Parameters.Add("#area", SqlDbType.Decimal).Value = textBox6.Text;
dad.UpdateCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.UpdateCommand.Parameters.Add("#cenro", SqlDbType.NVarChar).Value = textBox8.Text;
dad.UpdateCommand.Parameters.Add("#id", SqlDbType.Int).Value = ds.Tables[0].Rows[tblNamesBS.Position][0];
conn.Open();
dad.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
above the code i made a global function
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
BindingSource tblNamesBS = new BindingSource();
what seems to be the problem here??
oh and to add up i made a datagridview that has a double click event, below is my code:
private void dg_DoubleClick(object sender, EventArgs e)
{
try
{
button2.Visible = true;
button5.Visible = true;
DataTable dt = new DataTable();
SqlDataAdapter dad = new SqlDataAdapter("SELECT * FROM tblSchools WHERE Number ="+
Convert.ToInt16(dg.SelectedRows[0].Cells[0].Value.ToString()) + "", conn);
dad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
comboBox1.Text = dt.Rows[0][2].ToString();
textBox2.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
//dateTimePicker1.Value = dt.Rows[0][7];
textBox8.Text = dt.Rows[0][8].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
will this code affect my edit?
You have declared an empty data set
DataSet ds = new DataSet();
And later you try to access Table[0] in it but there isn't one defined.
I'm trying to do an update using CommandBuilder. The code works perfectly when the the code fetching the data is retrieved by a button command, but when I fetch the data from the page_load, update fails.
The program simply fetches data from a database then uses the sqlCommandBuilder to make updates on a specific table.
I can't figure out what is going on.
Here is is the Code that fails.
private Users users;
protected void Page_Load(object sender, EventArgs e)
{
users = (Users)Session["Users"];
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string selectQuery = "Select * from Candidate where Candidate_ID = " + users.Candidate_ID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectQuery, connection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Candidates");
ViewState["DATASET"] = dataSet;
ViewState["SELECT_QUERY"] = selectQuery;
if (dataSet.Tables["Candidates"].Rows.Count > 0)
{
DataRow dataRow = dataSet.Tables["Candidates"].Rows[0];
txtLastName.Text = dataRow["LastName"].ToString();
txtCity.Text = dataRow["City"].ToString();
ddlGender.SelectedValue = dataRow["Gender"].ToString();
lblStatus.Text = "";
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "No record with ID = " + txtCandidateID.Text;
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand((string)ViewState["SELECT_QUERY"], con);
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
DataSet ds = (DataSet)ViewState["DATASET"];
DataRow dr = ds.Tables["Candidates"].Rows[0];
dr["LastName"] = txtLastName.Text;
dr["Gender"] = ddlGender.SelectedValue;
dr["City"] = txtCity.Text;
int rowsUpdated = dataAdapter.Update(ds, "Candidates");
if (rowsUpdated == 0)
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "No rows updated";
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Green;
lblStatus.Text = rowsUpdated.ToString() + " row(s) updated";
}
}
Here is the code that works perfectly.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand((string)ViewState["SELECT_QUERY"], con);
SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter);
DataSet ds = (DataSet)ViewState["DATASET"];
DataRow dr = ds.Tables["Candidates"].Rows[0];
dr["LastName"] = txtLastName.Text;
dr["Gender"] = ddlGender.SelectedValue;
dr["City"] = txtCity.Text;
int rowsUpdated = dataAdapter.Update(ds, "Candidates");
if (rowsUpdated == 0)
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "No rows updated";
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Green;
lblStatus.Text = rowsUpdated.ToString() + " row(s) updated";
}
}
protected void btnFetchData_Click(object sender, EventArgs e)
{
users = (Users)Session["Users"];
string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string selectQuery = "Select * from Candidate where Candidate_ID = " + users.Candidate_ID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectQuery, connection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Candidates");
ViewState["DATASET"] = dataSet;
ViewState["SELECT_QUERY"] = selectQuery;
if (dataSet.Tables["Candidates"].Rows.Count > 0)
{
DataRow dataRow = dataSet.Tables["Candidates"].Rows[0];
txtLastName.Text = dataRow["LastName"].ToString();
txtCity.Text = dataRow["City"].ToString();
ddlGender.SelectedValue = dataRow["Gender"].ToString();
lblStatus.Text = "";
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "No record with ID = " + txtCandidateID.Text;
}
}
Did you miss a check on Page.IsPostBack?
Remember that in ASP.NET when you click a server button the code in the Page_Load is called before the code in the button click event.
Without
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// load data
}
}
the code that reloads the DATASET is executed again and, when you receive the control in the button click event, your changes are lost.
fisrt of all make a debug of your source code.
Create breakpoint on each line and check which values are stored in varibales.
Also make it for debug purpouse in a try catch block.
When you can understand where the error has been made you may check of to fix issue.
Which type of error you receive??
Another stuff you assume that user is always in session.Take care that aspnet use a custom method to recycle session and you can have session empty because iis application pool is restarted of has reached is "limit"
is a good practice check if session(value) is null before make the cast