I retrived values by the use of SqlCommand and SqlReader from column and stored in List<String> and the added to ComboBox(Type:DropDownList) but Eventhough i have deleted Some of this values from database Combobox is still showing it.
I am clearing items befor allocating by
mycombobox.Items.Clear();
It looks as it is not affected by values I retrive every time when the Form gets Loaded.
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
Thanks in advance.
Use the DataSource property of the Combobox instead of the adding the items one by one. So your code will be something like the following:
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection = new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
//Replace this part...
//foreach(string pname in namesCollection)
//cb.Items.Add(pname);
//With this...
cb.DataSource = namesCollection;
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
There is a similar question here
Hope this helps
Let's say the code to populate the ComboBox is placed in the populate_cb() method
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
Call populate_cb() method form form_load() and
Call from the place after the deletion process
You need to make sure your deletion process really deletes the records from database!
Related
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.
da.UpdateCommand.ExecuteNonQuery() is not getting executed
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
Don't use adapter.
And yes. Faster of all try to close connection and open new one for update operation.
try
{
UserMaster ObjUserMst = new UserMaster();
ObjUserMst.GetData("UPDATE MemberDetails SET Active = 0 WHERE Member_No = '" + txtmemberno.Text + "'");
MessageBox.Show("Installment Close Successfully.", "Close Installment", MessageBoxButtons.OK, MessageBoxIcon.Information);
btndebit.Visible = true;
btndebit.Visible = false;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), "btncloseinstallment_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
its get data code
public DataTable GetData(string Query)
{
string cn = GlobalClass.ConnectionStringGet();
Con = new SqlConnection(cn);
cmd = new SqlCommand();
cmd.Connection = Con;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
SqlTransaction ObjTrans = cmd.Connection.BeginTransaction();
cmd.Transaction = ObjTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
cmd.CommandTimeout = 500;
SqlDataReader dreader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dreader);
Con.Close();
Con.Dispose();
return dt;
}
i have winforms.
i have memberdetails Table - in this Active Field & its datatype is BIT. its
default value is 1. but i need to update it to 0.
1 = ture
0 = false
when i tried above code Active Field data didnt update
but i got message "Installment Close Successfully."
http://i.stack.imgur.com/mkuhW.png
http://i.stack.imgur.com/ToXFV.png
I upload my images on above link
help me guys.. sorry if i didnt explain very well bcz i m new here
ok i got it.
string constring = GlobalClass.ConnectionStringGet();
string sqlUpdate = "UPDATE MemberDetails SET Active = '0' WHERE Member_No = '" + txtmemberno.Text + "'";
SqlConnection conDatabase = new SqlConnection(constring);
SqlCommand cmdd = new SqlCommand(sqlUpdate, conDatabase);
conDatabase.Open();
cmdd.ExecuteNonQuery();
conDatabase.Close();
MessageBox.Show("Installment Close Successfully.");
its update Active Field 1 to 0 successfully.
I wrote this code but I do not know why this line gives error!
String sname = dr.GetString ("name");
My code:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
String sname = dr.GetString("name");
comboBox1.Items.Add(sname);
}
}
catch (Exception e)
{
// do smth about exception
}
First of all you have to check this again:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
Data Source=.; This is wrong and it will give you an error.
After that you can use the code below to achieve what you want. The code below also uses using statement to dispose the connection.
using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
SqlCommand command = new SqlCommand("select * from tbllogin", connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
}
}
reader.Close();
}
(Amazingly) GetString only take an index as parameter.
See MSDN
public override string GetString(int i)
With no other signatures :-(
However you could write:
String sname = dr.Item["name"].ToString();
MSDN says that SqlDataReader.GetString method accepts an int as a parameter, which is the index of the column.
What you need is this:
while (dr.Read())
{
String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
Here's your code:
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
try {
cn.Open(); dr = cmd.ExecuteReader();
while (dr.Read())
{ String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
}
catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }
The catch block wasn't written correctly, you missed the (Exception e) part.
I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}