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.
Related
I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
I have a search textbox in my windows form application and I want to search character by character means when I write h in textbox then shows result in datagridview of h and when I add h with a like ha in search textbox then shows result in datagridview of ha and its change results in datagridview from h to ha as same as mobile phone contacts searching. and I working like below:
public partial class Form2 : Form
{
SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Contact.mdf;Integrated Security=True;");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
bindDatagridview();
if (textBox1.Text != string.Empty)
{
search();
}
}
public void bindDatagridview()
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("Select * from contactsinfo", connection);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
//dataGridView1.DataBindings();
}
public void search()
{
da.SelectCommand = new SqlCommand("Select * from contactsinfo where ContactName = '" + textBox1.Text + "'", connection);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
clear();
}
}
But this only work when the form is load and the form is only loaded at first time:
Kindly suggest me what i do, waiting for your reply.
Thanks.
If you can load all contacts at once, then its simple. On form load get all contacts and save them in DataView. Then bind grid to this view:
DataView contactsView;
private void Form2_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
var da = new SqlDataAdapter("SELECT * FROM from contactsinfo", conn);
da.Fill(dt);
}
contactsView = dt.AsDataView();
dataGridView1.DataSource = contactsView;
}
Then just change row filter of DataView when text changes in filter TextBox:
private void textBox1_TextChanged(object sender, EventArgs e)
{
contactsView.RowFilter =
String.Format("ContactName LIKE '{0}%'", textBox1.Text);
}
If you can't pre-load all data, then you should use same TextChanged event to query for filtered data.
NOTE: You should handle ' in user input.
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.
I am having a problem in selecting a value from dropdown list. Regardless of whatever I choose only the first value is selected always. Please help...
Here is the code...
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection con;
String strcon = ConfigurationManager.AppSettings["Constr"].ToString();
try
{
if (!IsPostBack)
{
con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select user_name from user_details where role='USER'", con);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = "user_name";
DropDownList1.DataSource = ds.Tables[0].DefaultView;
DropDownList1.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
protected void Button6_Click(object sender, EventArgs e)
{
string Name = Session["name"].ToString();
SqlConnection con;
String strcon = ConfigurationManager.AppSettings["Constr"].ToString();
try
{
con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select user_name,Arival,late,Day_count from attedance where user_name='" + DropDownList1.SelectedItem.Text + "' ", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
Don't quite get your code. You've shown two button click event handlers.
The first populates the drop-down, so the first item will be selected (that's how it works).
The second one populates a gridview.
If the issue arises from clicking 'Button4' (rename buttons to make it clear what they do), then that's your issue surely?
Also, you're not closing your SqlConnection. Use a using block:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Do work here
}
EDIT: Ah, just noticed the (!IsPostBack).
Is ViewState enabled for the drop-down?