I have this web written in C# , that provides a table for user with these data ( ID , FROM , TITLE , MESSAGE ) Table name on database is MessagesTable
My question is how can I use Entity Framework to upload data on the table , I used to do it using ConnectionStrings.
public partial class UsersEF : System.Web.UI.Page
{
static string ConnStr = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
int SelectedID = 0;
SqlConnection con;
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//GridViewRow grdrw = GridView1.Rows[e.RowIndex];
//SelectedID = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
SelectedID = int.Parse(e.NewValues["Id"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE MessagesTable set [From]=#From ,[To] =#To ,Title =#Title ,Message = #Message WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#id",SqlDbType.Int)).Value=SelectedID;
cmd.Parameters.Add(new SqlParameter("#From",SqlDbType.NVarChar ,50)).Value = e.NewValues["From"].ToString();
cmd.Parameters.Add(new SqlParameter("#To", SqlDbType.NVarChar, 50)).Value= e.NewValues["To"].ToString();
cmd.Parameters.Add(new SqlParameter("#Title", SqlDbType.NVarChar, 50)).Value = e.NewValues["Title"].ToString();
cmd.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar, 150)).Value = e.NewValues["Message"].ToString();
if (cmd.ExecuteNonQuery() > 0)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindGrid();
}
else {
e.Cancel = false;
};
}
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
// SelectedID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[0].Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedID =int.Parse (GridView1.SelectedRow.Cells[0].Text);
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
SelectedID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[0].Text);
BindGrid();
//SelectedID = int.Parse();
}
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConnStr);
con.Open();
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
var context = new TestDBEntities();
//DataTable table = new DataTable();
var table = context.MessagesTable.ToList();
/*
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Id,[From],[To],Title,Message from MessagesTable ";
//DataSet dataSet = new DataSet();
DataTable table=new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
*/
GridView1.DataSource = table;//dataSet.Tables[0];
GridView1.DataBind();
}
}
You can update it this way using EF -
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SelectedID = int.Parse(e.NewValues["Id"].ToString());
// retrieve from db
var messages = this.context.MessagesTable.FirstOrDefault(x=>x.id == SelectedID);
// update values
messages.From = int.Parse(e.NewValues["From"].ToString());
messages.To= int.Parse(e.NewValues["To"].ToString());
messages.Title = int.Parse(e.NewValues["Title"].ToString());
messages.Message= int.Parse(e.NewValues["Message"].ToString());
//Save changes into db
this.context.MessagesTable.Update(messages);
this.context.SaveChanges();
}
So I have written my code but every time i try to execute it it says "exception unhandled System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'" and it always shows it at the line that says da.Fill(dt);
please tell me how to fix it
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The best practice for handling connection objects is to store them in a local variable and dispose them as soon as possible. You don't need to worry overhead opening and closing connections; they are actually managed in a pool and it's very efficient.
You are storing your connection at the class level and not handling the connection properly. If you store it at the class level, it could time out between button clicks, and it's taking up resources the whole time. Close or dipose the connection right away, which will return it to the connection pool.
To fix, follow this sort of pattern:
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
//Get rid of member variable for the connection. Add constant for connection string.
private const string ConnectionString = #"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True";
private void button1_Click(object sender, EventArgs e)
{
//Use using and use a local variable for the connection
using (var con=new SqlConnection(this.ConnectionString))
{
con.Open();
var cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
//Create a new connection each time you need one
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
else if (comboBox1.Text == "EmployeeName")
{
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
your connection property is not intialised.Click button_click to have your connection intialised.or inside Textbox5_textchanged check for connection con.Isopen else intialize connection object again.
I think you shoul initialize connection object first of all.
You can change your code with the below code and pls return result:
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(con == null)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
}
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter da = null;
DataTable dt = new DataTable();
if(comboBox1.Text == "EmployeeID")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else if (comboBox1.Text == "EmployeeName")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else
{
}
dataGridView1.DataSource = dt;
}
Your connection has not been initialized at the time you're textBox5 text has changed. Move it to your constructor.
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
There is a textbox which searches the value from the Gridview. When the value displays then Every time I click Edit it goes to the first Index Row of the Gridview. I want to only edit the row which has been searched by ID.
For example if I search a value that is in row 8. It displays row 8 which is fine but when I click edit it goes to first row again. Why is this happening?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory", con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory where (Part like '%" + txtSearch.Text + "%') or (Brand like '%" + txtSearch.Text + "%' )", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox Part = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPart");
TextBox Description = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Qty = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtQty");
DropDownList Brand = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlBrand");
TextBox ItemType = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtItemType");
SqlCommand cmd = new SqlCommand("update tblInventory set Part='" + Part.Text + "',Description='" + Description.Text + "',Qty='" + Qty.Text + "',Brand='" + Brand.Text + "',ItemType='" + ItemType.Text + "' where ID=" + id, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
You need to modify your BindGridView Method, it will take care the problem.
Now when you a search a value in any Row and it displays the results, and when edit is clicked, it will stay on the selected Row.
txtSearch is just the ID of your Search TextBox.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView(this.txtSearch.Text);
}
}
protected void BindGridView(string column1)
{
SqlCommand cmd = new SqlCommand("select * from table1 where (column1 like '%" + txtSearch.Text + "%')", con);
con.Open();
cmd.Parameters.AddWithValue("#column1 ", column1 );
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView(this.txtSearch.Text);
}
I'm using ASP.NET, I have one refresh button. one listbox. two textboxes. on .cs side, I have a method, which clears the listbox and refreshes the listbox, if I put it into page load, the listbox selectedindexchanged event stops working. Why is this?
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection cnn = new SqlConnection("Initial Catalog=bigum;Data Source=localhost;Integrated Security=SSPI;");
protected void refresh()
{
ListBox1.Items.Clear();
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT OgrenciFirstName,OgrenciLastName FROM ogrenciler", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ListBox1.Items.Add(dr.GetString(0) + " " + dr.GetString(1));
}
}
cnn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
refresh();
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex > -1)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT OgrenciFirstName,OgrenciLastName FROM ogrenciler WHERE OgrenciID = #mynumber", cnn);
cmd.Parameters.AddWithValue("#mynumber", (ListBox1.SelectedIndex + 1));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
TextBox1.Text = dr.GetString(0);
TextBox2.Text = dr.GetString(1);
}
}
cnn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
refresh();
}
}
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();
}
}
}