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;
}
}
Related
How can I set the first line of Combobox empty in my code?
This is the function that is called when the form loads and it inserts the options on the Combobox.
private void preencherComboDpt()
{ carregandoComboDepartamentos = true;
NpgsqlConnection conn = new NpgsqlConnection();
try
{
conn = new NpgsqlConnection(connstring);
string query = "select * from departamento order by departamento";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
cmd.CommandText = query;
conn.Open();
NpgsqlDataReader drd = cmd.ExecuteReader();
DataTable dt = new DataTable("tabela");
dt.Columns.Add("departamento_id", typeof(int));
dt.Columns.Add("departamento", typeof(string));
while (drd.Read())
{
DataRow row = dt.NewRow();
row["departamento_id"] = int.Parse(drd["departamento_id"].ToString());
row["departamento"] = drd["departamento"].ToString();
dt.Rows.Add(row);
}
cobUnivDep.DataSource = dt.DefaultView;
cobUnivDep.DisplayMember = "departamento";
cobUnivDep.ValueMember = "departamento_id";
}
catch
{
MessageBox.Show("Error ");
}
carregandoComboDepartamentos = false;
}
I already tried inserting the line cobUnivDep.SelectedIndex = null, but it doesn't work.
I have two GridView. First is called "gvImage" which is the category gridview with checkbox for selection. Second GridView is called "GridView1", the Second GridView populates basing on the value selected in the First GridView, here I am able to populate the record in Second GridView only for one category checked (selected) from the First GridView, but when I check (select) multiple category from the First GridView(gvImage) then it is not populating the multiple category record in the Second GridView(GridView1). Please help me to get this, below is my Code behind:
protected void btn_Submit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
String strConnString = ConfigurationManager.ConnectionStrings["CONNECTION1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string str = "SELECT * FROM AllProduct WHERE PId =#PId";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("#PId", row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text);
//this.ExecuteQuery(cmd, "SELECT");
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
GridView1.Enabled = true;
}
}
}
else if (objDs.Tables[0].Rows.Count == 0)
{
GridView1.DataSource = null;
GridView1.Visible = false;
}
}
}
}
}
The problem is that you bind the second grid for each selected checkbox which will essentially always replace the data that has been bound, so that you only see the results for the last selected checkbox. You need to combine the results and bind outside the foreach
protected void btn_Submit_Click(object sender, EventArgs e)
{
DataTable combinedDataTable;
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
DataTable data = //Data from database for this checkbox
if(combinedDataTable != null)
combinedDataTable.Merge(data);
else
combinedDataTable = data;
}
}
}
GridView1.DataSource = combinedDataTable;
GridView1.DataBind();
}
or even better, just collect which checkboxes are checked first, and then get the results in one query:
protected void btn_Submit_Click(object sender, EventArgs e)
{
List<string> selectedCheckboxes = new List<string>()
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
selectedCheckboxes.Add(row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text);
}
}
}
String strConnString = ConfigurationManager.ConnectionStrings["CONNECTION1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string str = "SELECT * FROM AllProduct WHERE PId in ";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
List<string> parametersNames = new List<string>();
for (int i = 0; i < selectedCheckboxes.Count; i++)
{
var parameterName = "#PId" + i;
cmd.Parameters.AddWithValue(parameterName, selectedCheckboxes[i]);
parametersNames.Add(parameterName);
}
str += "(" + String.Join(",", parametersNames) + ")";
str += " AND TransactionDate BETWEEN #From AND #To";
cmd.Parameters.AddWithValue("#From", DateTime.Parse(txtFrom.Text));
cmd.Parameters.AddWithValue("#To", DateTime.Parse(txtTo.Text));
cmd.CommandText = str;
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
GridView1.Enabled = true;
}
}
}
else if (objDs.Tables[0].Rows.Count == 0)
{
GridView1.DataSource = null;
GridView1.Visible = false;
}
}
I have a strange problem,
I'm working with win-form which is coding in c#..and sql server
In a form I have a Combo-box which is collected data by the database(say 1).
and later I have to Insert that particular value/member details into another database(say 2)
Here My problem raises,,Once My combo-box any value is inserted into 2nd database,that particular value/member should not visible in the combo-box for the next time on the same day..
Of course Here I'm using datetimepicker..
Here I'm using following code...and Of-course it is wrong..Please Help me
SqlCommand cmd1 = new SqlCommand("select employee_id,Empployee_Name,date from dailyattendance", cn);
SqlDataReader sdr;
DataTable dt = new DataTable();
sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
string employeeid = (string)sdr["employee_id"];
string employeename = (string)sdr["Empployee_Name"];
string date = (string)sdr["date"];
try
{
//cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader sdr1;
DataTable dt1=new DataTable();
sdr1 = cmd.ExecuteReader();
dt1.Load(sdr1);
if (sdr1.Read())
{
string date1=dateTimePicker1.Value.ToString("dd/MM/yyyy");
if ()//here the main problem
{
string employeeid1 = (string)sdr1["employee_id"];
string employeename1 = (string)sdr1["employee_name"];
comboBox1.DisplayMember = employeeid1;
comboBox1.DisplayMember = employeename1;
comboBox1.DataSource=dt1;
cn.Close();
}
}
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
string query = "select employee_id,employee_name,image_of_employee,image_path from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "')";//Here added a new query which is working
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dtr);
foreach (DataRow row in dt.Rows)
{
var name = (string)row["employee_name"];
row["employee_name"] = name.Trim();
}
comboBox1.ValueMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
listBox1.ValueMember = "employee_id";
listBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
listBox1.DataSource = dt;
comboBox1.SelectedItem = null;
listBox1.SelectedItem = null;
cn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Simply at query added some workable logic
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();
}
}
}
I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}
you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.