this code is working good. But i want to search data without click button. when i will write Employee name if it will exists in table it will show my information otherwise i will insert data. Please help me...
protected void btnSubmit_Click(object sender, EventArgs e){
var sqlQuery = "SELECT EmployeeID, Weight, Amount FROM Supplier where EmployeeName= '" + TextBox2.Text+ "'";
//Create Instance for DataSet
var DS = new DataSet();
//Create Instance for SqlConnection
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString);
//Create Instance for SqlCommand
var cmd = new SqlCommand(sqlQuery, conn);
var DA = new SqlDataAdapter(cmd);
DS.Clear();
try{
DA.Fill(DS);
}
catch (Exception ex){}
foreach (DataRow row in DS.Tables[0].Rows){
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
You could use TextChanged event handler and a parameterized query for sql injection protection. However, the code below be forwarned is costly because it has to access the Database from time to time.
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
String connString = ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
String strSQL = "SELECT EmployeeID, Weight, Amount FROM Supplier where EmployeeName=#EmployeeName";
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = TextBox2.Text;
using (SqlDataAdapter DA = new SqlDataAdapter(cmd))
{
DA.SelectCommand = cmd;
try
{
DataSet DS = new DataSet();
DA.Fill(DS);
foreach (DataRow row in DS.Tables[0].Rows)
{
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
catch (Exception ex)
{
}
}
}
}
}
However, you could probably just cached the whole table and then from there do the query instead of going to the database from time to time like:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
var query = from myRow in myDataTable.AsEnumerable()
where r.Field<string>("EmployeeName")==TextBox2.Text
select new
{
EmployeeID = myRow.Field<int>("EmployeeID"),
Weight = contact.Field<int>("Weight"),
Amount = order.Field<double>("Amount")
};
foreach (var row in query)
{
txtBoxId.Text = row.Employee.ToString();
txtboxw.Text = row.Weight.ToString();
txtboxam.Text = row.Amount.ToString();
}
}
I've got a different approach. Assuming the contents of your Supplier table do not change frequently, I'd suggest caching the contents of that table on page load and then just reference that table when the text in that text box is changed.
private DataTable _suppliers;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlQuery = "SELECT EmployeeID, Weight, Amount, EmployeeName FROM Supplier";
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString);
_suppliers = new DataTable();
var cmd = new SqlCommand(sqlQuery, conn);
conn.Open();
var SDA = new SqlDataAdapter(cmd);
SDA.Fill(_suppliers);
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(_suppliers);
DV.RowFilter = string.Format("EmployeeName LIKE '%{0}%'", TextBox2.Text);
if (DV.Count == 1)
{
var row = DV[0];
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
Additionally, you may want to look into using an updatepanel to handle the text changed event asynchronously instead of using the TextChanged event.
Related
I'm trying to build a search function using a textbox on a webform gridview which populates records from a remote mysql database.
I'm stuck with the syntax error, however when I check the manual, and try to follow the correct syntax, the error persist.
I'm using Asp.net 2013 with a remote mysql database.
public partial class resitDB : System.Web.UI.Page
{
string myConn = "SERVER=110.4.**.***;PORT=****;DATABASE= ***** ;UID=**** ;PASSWORD=***** ;";
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["username"].ToString();
if (!IsPostBack)
{
using (MySqlConnection conn = new MySqlConnection(myConn))
{
using (MySqlCommand com = new MySqlCommand("SELECT * FROM `tblresit`", conn))
{
using (MySqlDataAdapter da = new MySqlDataAdapter())
{
com.Connection = conn;
da.SelectCommand = com;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
//here
searchData("");
}
public void searchData(string valueSearch)
{
//the sql error is here
string query = "SELECT * FROM 'tblresit' WHERE CONCAT ('custName','IdResit','resitId','custId') LIKE '%"+valueSearch+"%' )";
MySqlConnection con = new MySqlConnection(myConn);
MySqlCommand com = new MySqlCommand(query, con);
MySqlDataAdapter adapter = new MySqlDataAdapter(com);
dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string valueSearch = searchTxt.Text.ToString();
searchData(valueSearch);
}
}
My guess is that you want to write something like
SELECT *
FROM tblresit
WHERE custName LIKE '%valueSearch%'
or IdResit LIKE '%valueSearch%'
or resitId LIKE '%valueSearch%'
or custId LIKE '%valueSearch%'
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 myCode:
private void frmChart_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable group by UserName",Con);
Con.Open();
SqlDataReader reader = cmdSum.ExecuteReader();
chart1.DataBindTable(reader,"sum(Value)");
}
foreach (Series series in chart1.Series)
{
series.CustomProperties = "DrawingStyle=LightToDark";
}
}
It shows me an error in chart1.DatabindTable. also I try another method but I could not handle it.
If all you're trying to do is to bind a data table, then just do this:
private void Form1_Load(object sender, EventArgs e)
{
string sql = "your sql here";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connectionString);
DataTable dt = new DataTable();
adapter.Fill(dt);
chart1.DataBindTable(dt.DefaultView, "UserName");
}
Note when calling DataBindTable you have to use "UserName" (xField). Not Value or Sum(Value).
check you values into reader.. if you have values,
try replacing
chart1.DataBindTable(reader,"sum(Value)");
with
chart1.DataBindTable(reader,"Value");
once you sum up values into query you need not to mention sum again, your Value parameter will have sum
Edit --- Updated Code..
private void frmChart_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable group by UserName", Con);
Con.Open();
SqlDataReader reader = cmdSum.ExecuteReader();
while (reader.Read())
{
chart1.DataBindTable(reader, reader["Value"]);
}
}
foreach (Series series in chart1.Series)
{
series.CustomProperties = "DrawingStyle=LightToDark";
}
}
//.aspx.cs code:
protected void ddldistrict_SelectedIndexChanged(object sender, EventArgs e)
{
try {
ddltaluka.Enabled = true;
string d1 = ddldistrict.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*******;Database=guj_data;");
conn.Open();
string sql = "SELECT tname FROM taluka_geo_bnd_box WHERE district='"+d1+"'";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
ddltaluka.DataSource = ds;
ddltaluka.DataTextField = "tname";
ddltaluka.DataBind();
conn.Close();
}
catch(Exception e3)
{
throw e3;
}
}
protected void ddltaluka_SelectedIndexChanged(object sender, EventArgs e)
{
try {
ddlvillage.Enabled = true;
string t1 = ddltaluka.Text;
string d1 = ddldistrict.Text;
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*****;Database=guj_data;");
conn.Open();
string sql = "SELECT vname FROM village_boundary_geo_bnd_box WHERE tname='"+t1+"' AND district='"+d1+"'";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
ddlvillage.DataSource = ds;
ddlvillage.DataTextField = "vname";
ddlvillage.DataBind();
conn.Close();
}
catch(Exception e4)
{
throw e4;
}
}
If I am understanding you correctly;
ddlvillage data bind happens at page load
when the method ddltaluka_selectedIndexChanged is called, you try to bind new data do it but it goes back to the original ddlVillage list?
If this is the case you need to only do the initial databind for ddlVillage on the initial page load and not each post back
if (!IsPostBack)
{
//bind your initial data here
}
Good day to all. I have this code that populates the Datagridview. And I tried to edit it. But it seems I can't save any changes to database. Though I'm not getting any errors. Any help would be much appreciated. Thanks alot!
private void FrmViewCustomer_Load(object sender, EventArgs e)
{
string query = "SELECT CONCAT(firstname,', ',lastname) AS NAME, orderedgood AS OrderedGood FROM customer c;";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
{
conn.Open();
using (MySqlCommand command = new MySqlCommand(query, conn))
{
using (adapter = new MySqlDataAdapter(command))
{
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = false;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
this.adapter.Update(dt);
}
MyTable
id name
1 John
2 Carl
3 Sam
C# Code behind:
public partial class Form1 : Form
{
DataTable dt = null;
DataGridView dgv = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from MyTable;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv = new DataGridView();
dgv.AllowUserToAddRows = false;
dgv.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;
this.Controls.Add(dgv);
}
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 0)
{
dgv.CancelEdit();
}
}
void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["id"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value+"";
string sql = string.Format("UPDATE `MyTable` SET `{0}` = '{1}' WHERE ID = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}