This is my code on my FormLoad-event
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
I want two options to populate an autocomplete textbox during typing in textbox:
By name
By number
However it doesn't work. I already tryed this in my TextChanged-event, but with no luck. Can somebody help me?
Rather than using optional AutoCompleteSource update all the data into one source. This wont be any problem, since the person wont have to select the options, rather he will type by deciding his option.
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
dReader = cmd.ExecuteReader();
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
or if you want to use the older option,
namesCollection.RemoveAll();
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
namesCollection.RemoveAll();
if (radioName.checked==true)
{
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader[0].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
Notice
namesCollection.RemoveAll();
Related
how can I insert data from datagridview and textboxes at same time with one button click in one table. here is my code I use foreachloop to insert from DataGridview but it insert null
any help appreciate.
SqlCommand cmd, cmd1, cmd2, cmd3;
con.Open();
cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd1 = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd1.Parameters.AddWithValue("#sdetail", sid);
cmd1.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd2 = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd2.Parameters.AddWithValue("#customer", customerid);
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
}
if (cmd.ExecuteNonQuery() == 1)
{
if (cmd1.ExecuteNonQuery() == 1) {
if (cmd2.ExecuteNonQuery() == 1)
{
Perhaps:
using con = new SqlCommand(...);
con.Open();
var tran = con.BeginTransaction();
var cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd.Parameters.AddWithValue("#sdetail", sid);
cmd.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd.Parameters.AddWithValue("#customer", customerid);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
cmd.ExecuteNonQuery();
}
tran.Commit();
And wrap the whole thing(apart from the using) in a try catch (I would have done it but I'm on a cellphone; there is no code indent button) and put tran.Rollback(); in the catch
I have listview control in my page. I gets populated onPage load as well as when new record entered in the table. Problem is after performing InsertOperation I am calling It's bind method again but it doesn't refresh its data. Hence I debugged it & executed actual query in SQL & query returns with added rows.
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
this.bindBulkPricing();
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
private void bindBulkPricing()
{
string action = Request.QueryString("action").ToString;
if (action == "new") {
productID.Text = rowNumber;
}
try {
string str = "select * from bulk_pricing where productID = #productID";
string conString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString;
MySqlConnection con = new MySqlConnection(conString);
MySqlCommand cmd = new MySqlCommand(str);
cmd.Parameters.AddWithValue("#productID", productID.Text);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
bulkPriceList.DataSource = dt;
bulkPriceList.DataBind();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.bindBulkPricing();
} catch (Exception ex) {
Response.Write(ex);
}
}
You only run cmd.ExecuteNonQuery() after run this.bindBulkPricing(). I hope it will work for you.
I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}
con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
Label1.Text = dr["Calf_ID"].ToString();
Label2.Text = dr["Plant"].ToString();
Label3.Text = dr["date1"].ToString();
Label4.Text = dr["Event"].ToString();
}
con.Close();
I am using this code but it retrieves only one row from table I want all data from Table.
You can try a grid view
con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader())
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
con.Close();
con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
Label1.Text += dr["Calf_ID"].ToString();
Label2.Text += dr["Plant"].ToString();
Label3.Text += dr["date1"].ToString();
Label4.Text += dr["Event"].ToString();
}
con.Close();
Public class Employee
{
public int EmployeeId{get;set;}
public string Name{get;set;}
}
//ADO.NET CODES
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
string cs = ConfigurationManager.ConnectionString["DBCS"].ConnectionStrings;
using(SqlConnection con = ne SqlConnection(cs))
{
List<Employee> employee = new List<Employee>();
SqlCommand cmd = new SqlCommand("select * from Employee",con);
cmd.commandType = CommandType.Text;
con.Open();
SqlReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Employee emp = new Employee();
emp.EmployeeId = Convert.ToInt32(rdr["EmployeeId"]);
emp.Name = rdr["Name"].ToString();
employee.Add(emp);
}
}
On MVC5 you can use:
List<EntityName> varName = db.EntityName.ToList(); //This selects all rows from the table
Then you can iterate your list to display the info string/label
SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
while (reader.Read())
{
string s = reader["Role"].ToString();
}
reader.Close();
conn1.Close();
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
if(s.Equals("teacher"))
{
GridView2.DataSource = rdr;
GridView2.DataBind();
}
rdr.Close();
//reader.Close();
}
catch
{
conn.Close();
}
I'm getting error in the below connection saying s does not exist in the current context. How to use the multiple datareaders please help me.
Declare string s out of hte loop
string s;
while (reader.Read())
{
s = reader["Role"].ToString();
}
SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
string s = String.Empty;
while (reader.Read())
s = reader["Role"].ToString();