I am a beginner in C# and using MS Visual Studio 2010. Ans my problem is I am inserting data through textbox in a table named as (tbl_employees) and saving it successfully.
After saving when I see the table the new inserted data is not showing in tbl_employee even after updating.
Here is my code for updating table
private void btnupdate_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tbl_employees";
da = new System.Data.SqlClient.SqlDataAdapter(sql , conString);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow row = ds.Tables[0].Rows[inc];
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
MessageBox.Show("Now Table is updated too. . . ");
}
Code with ease to understand and implement
Insert
private void Insert()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Insert into YourTable Select (#Val1,#Val2,#Val3)";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Update
private void Update()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Update YourTable Set Field1=#Val1,Field2=#Val2,Field3=#Val3 Where YourPrimaryKey=#Key";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
command.Parameters.Add("#Key",txt4.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Select
private DataTable Get()
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Select * From YourTable";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
using(var reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
{
dt.Load(reader);
}
con.Close();
}
}
return dt;
}
So now you have a Get method that returns DataTable , now you need a grid to display that data. Quite simple.
ASP.Net
private void BindGrid()
{
gridview1.DataSource = Get();
gridView1.DataBind();
}
Winforms
Same as above except we need not call DataBind().
Related
I'm currently practicing to make a barcode attendance application. After scanning the barcode, the barcode is automatically showing in a text box. There is a add button to send the barcode to the database. But when I click the add button only a blank dataset is adding.(It's working when directly type in the textbox)
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
Here is the add button code
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into student_att (`id`, `nic`, `name`, `address`, `number`, `batch`) select* from student_dt where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
try
{
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1st of all, your queries are quite weird, when you do INSERT, I dont see anywhere what do you actually insert (no data specified in your code), it should be like:
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!=string.Empty)
{
//using means it will close and dispose the classes by it self! So no need to type Close() or Dispose() methods.
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
bool bAllOK = false; //using and helping with some custom flag to get it all right
string query1 = #"INSERT INTO student_att (id, nic, name, address, number, batch) VALUES (#id, #nic, #name, #address, #number, #batch)";
string query2 = #"SELECT * FROM studetnt_att WHERE nibm_id LIKE #myText%";
//1. INSERT:
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.Parameters.AddWithValue("#id", 1); //get new ID, best is to look for the last one in the DB, and increment by 1
cmd.Parameters.AddWithValue("#nic", "nickname1"); //get his nick name
//same way and and set all the other 4 parameters for name, address, number and batch here
try
{
connection.Open();
command.ExecuteNonQuery();
bAllOK = true;
}
catch(SqlException)
{
// error here if occures
}
}
if(bAllOK)
{
//2. SELECT:
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.Parameters.AddWithValue("#myText", textBox1.Text);
DataTable table = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
dataGridView2.DataSource = table;
}
}
}
}
}
else
MessageBox.Show("Please type some name...");
}
The 2nd query makes no sence, since you are looking for nibm_id is looking for IDS which starts with the number in textBox. Is that really what you are looking for? LIKE SOMETHING% means that it looks for SOMETHINGS which starts with that.
in my program when i delete a record, it deleted from database access and from the DataGridView , but when i close the window and open it again the record appear again in DataGridView ,Although it deleted from database access ,Here is my code :
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
command.Connection = connection;
string query = " delete from Hoteldb where ID= " +textBox0.Text + "";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
public void BindGridView()
{
string strSQL = "SELECT * FROM Hoteldb";
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
dataGridView1.DataSource = table;
connection.Close();
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
int RowsAffected = 0;
connection.Open();
string query = "DELETE FROM Hoteldb WHERE ID=#ID";
command = new OleDBCommand(query);
command.Connection = connection;
cmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.WChar, 150, "ID"));
cmd.Parameters["#ID"].Value = textBox0.Text.Trim()
RowsAffected = command.ExecuteNonQuery();
if(RowsAffected > 0)
{
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
else
{
MessageBox.Show("There was nothing to be deleted");
}
}
public void BindGridView()
{
connection.Open();
string strSQL = "SELECT * FROM Hoteldb";
cmd = new OleDbCommand(strSQL);
cmd.Connection = connection;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Hoteldb");
dataGridView1.DataSource = ds.Tables["Hoteldb"].DefaultView
connection.Close();
}
I'm having trouble updating data from a data grid view with the use of a button. The text is editable but the changes does not save to the SQLite database. any ideas?
private void ProjectsAdmin_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'seniorProjectsDataSet2.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.seniorProjectsDataSet2.DataTable1);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex != 3) //ignore header row and any column that doesnt have file name
return;
var filename = dataGridView1.CurrentCell.Value.ToString();
if (File.Exists(filename))
Process.Start(filename);
}
private void updateData_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection();
dataGridView1.EndEdit();
dataTable1TableAdapter.Adapter.Update(seniorProjectsDataSet.Tables[0]);
for (int i = 0; i < seniorProjectsDataSet.Tables[0].Rows.Count; i++)
{
seniorProjectsDataSet.Tables[0].Rows[i].AcceptChanges();
}
}
}
}
I solved the problem without a Button. In the following code I´ll give you a example how the connection and the update works with a mysql-database (update in runtime):
CODE
DataTable dt = null;
DataGridView dgv1 = null;
If the form load you have to set your dt variable to a new datatable:
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from try.data ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = false;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
You have to set two events: CellValidating
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
and the CellValidating Event:
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["Eid"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `try`.`data` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This aktually works with MySql but in Sql are "Equal" components like the SqlConnection or the SqlCommand... I hope this solve you problem. Have a nice day!
using System.Data.SQLite;
SQLiteConnection con = new SQLiteConnection("Data Source=C:\\Cogs\\bin\\Release\\db\\my_database_file.db");
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [my_table]";
con.Open();
cmd.ExecuteNonQuery();
DataTable dta = new DataTable();
SQLiteDataAdapter dataadp = new SQLiteDataAdapter(cmd);
dataadp.Fill(dta);
dataGridView1.DataSource = dta;
con.Close();
I am writing this code for deleting selected row from datagridview and database at a time.
but i got the error in "deleteButton.Click"
deleteButton.Click += new System.EventHandler(this.DeleteRecord);
private DeleteRecord(object sender, EventArgs e)
{
foreach(DataGridViewRow row in DataGridView1.SelectedRows)
{
int rowIdToDelete = row.Cells[ID].Value;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Record] WHERE ID = " + rowIdToDelete;
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
}
}
}
Wrap rowIdToDelete within quotes.
string query = "DELETE FROM [Record] WHERE ID = " + "'rowIdToDelete'";
Also if ID is column name with add double quotes,
int rowIdToDelete = row.Cells["ID"].Value;
I'm just starting out at asp.net c# and I have been given a task to generate the available doctors upon the given values in a drop-down list.
I have 3 drop-down lists, (1)PROVINCE, (2)CITY, (3)SPECIALIZATION and a search button.
After the user selects the values of 3 drop-down lists and hits the search button it will print a table containing the available doctor.
I know that the key is on the search button, but I don't exactly know what to put under the search button. Can you help me out please?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("select distinct emed_accredited_providers.SPECIALIZATION from emed_accredited_providers inner join emed_doctors_hospitals on emed_accredited_providers.DOCTOR_CODE = emed_doctors_hospitals.DOCTOR_CODE where CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPECIALIZATION";
ddlSpec.DataValueField = "SPECIALIZATION";
ddlSpec.DataBind();
}
protected void btnDocs_Click(object sender, EventArgs e)
{
}
}
}
string query = string.Empty;
if (ddlProvince.SelectedIndex != -1)
{
query = query + " and PROVINCE_CODE=" + ddlProvince.SelectedValue;
}
if (ddlCity.SelectedIndex != -1)
{
query = query + " and CITY_CODE=" + ddlProvince.SelectedValue;
}
if (ddlSpec.SelectedIndex != -1)
{
query = query + " and SPECIALIZATION=" + ddlProvince.SelectedValue;
}
string tQuery = "Select * from Doc";
if (query.Length > 0)
{
query = query.Remove(0, 4);
tQuery = tQuery + query;
}
// Exeucate -- tQuery
// Modify table name or field name.
get the selected values from the drop down list
pass the selected values to your search function. (It depends on your logic, I mean if user select values from only one drop down, from only two drop down your search query may differ).
get the return values from your search function and bind it to your table (grid view)
Also have a look at the DropDownList.SelectedIndex Property
to bind the gridview you can do something similar to this
private void BindGrid ()
{
var dt = new DataTable();
var connection = new SqlConnection(YOUR CONNECTION);
try
{
connection.Open();
var query = "YOUR SEARCH QUERY";
var sqlCmd = new SqlCommand(query, connection);
var sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
//
}
finally
{
connection.Close();
}
}