I want to reload the updated record in gridview but its not working. Grid View reloads after i insert any new record but not reloads after i update the record. Although the record is saved in the Database and when i restart the application, the gridview load the updated record. I don't know why it's not reloading data when i update but reload data when i insert new record, Although i am calling the same function as i called in insertion
Here is Insert Code
private void InsertEmployee()
{
if (tbName.Text != "" && mtbCNIC.Text != "" && cBoxBloodGroup.SelectedIndex != -1 && cBoxMaritialStatus.SelectedIndex != -1 && tbAddress.Text != "" && tbFatherName.Text != "" && cBoxGender.SelectedIndex != -1 && tbPerAddress.Text != "")
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(emp_id),0)+1 FROM EMP_Master", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();
{
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO EMP_Master (emp_id , emp_name,emp_fathername,emp_nic,emp_gender,emp_contact,emp_dob,emp_bloodgroup,emp_maritialstatus,emp_address,emp_per_address,emp_picture)VALUES(#emp_id , #emp_name,#emp_fathername,#emp_nic,#emp_gender,#emp_contact,#emp_dob,#emp_bloodgroup,#emp_maritialstatus,#emp_address,#emp_per_address,#emp_picture)", con))
{
//con.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#emp_id", tbID.Text);
cmd1.Parameters.AddWithValue("#emp_name", tbName.Text);
cmd1.Parameters.AddWithValue("#emp_fathername", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#emp_nic",mtbCNIC.Text);
//string tbMaskCNIC = mtbCNIC.Text;
//tbMaskCNIC = tbMaskCNIC.Replace("-","");
//cmd1.Parameters.AddWithValue("#emp_nic", int.Parse(tbMaskCNIC));
cmd1.Parameters.Add("#emp_gender", SqlDbType.VarChar, 50);
cmd1.Parameters["#emp_gender"].Value = cBoxGender.SelectedItem;
cmd1.Parameters.AddWithValue("#emp_contact", tbContact.Text);
cmd1.Parameters.AddWithValue("#emp_dob", dtpBirth.Value.Date);
cmd1.Parameters.AddWithValue("#emp_bloodgroup",cBoxBloodGroup.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_maritialstatus",cBoxMaritialStatus.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#emp_per_address", tbPerAddress.Text);
cmd1.Parameters.AddWithValue("#emp_picture", SaveImage());
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Has been Saved Successfully !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGridView();
ResetForm();
tbName.Focus();
}
}
}
}
else
{
MessageBox.Show("All Fields are Mandatory !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
tbName.Focus();
}
//catch (Exception)
//{
// MessageBox.Show("Something is wrong");
//}
}
and here is the update code
private void UpdateEmployee()
{
try
{
//if (tbName.Text != "" && mtbCNIC.Text != "" && tbContact.Text != "" && tbAddress.Text != "" && tbFatherName.Text != "" && cBoxBloodGroup.SelectedIndex != -1 && cBoxGender.SelectedIndex != -1 && tbPerAddress.Text != "" && dtpBirth.Text != "")
//{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
{
using (SqlCommand cmd1 = new SqlCommand("UPDATE EMP_Master SET emp_name=#emp_name,emp_fathername=#emp_fathername,emp_nic=#emp_nic,emp_gender=#emp_gender,emp_contact=#emp_contact,emp_dob=#emp_dob,emp_bloodgroup=#emp_bloodgroup,emp_maritialstatus=#emp_maritialstatus,emp_address=#emp_address,emp_per_address=#emp_per_address,emp_picture=#emp_picture WHERE emp_id=#emp_id", con))
{
con.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#emp_id", tbID.Text);
cmd1.Parameters.AddWithValue("#emp_name", tbName.Text);
cmd1.Parameters.AddWithValue("#emp_fathername", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#emp_nic", mtbCNIC.Text);
cmd1.Parameters.Add("#emp_gender", SqlDbType.VarChar, 50);
cmd1.Parameters["#emp_gender"].Value = cBoxGender.SelectedItem;
cmd1.Parameters.AddWithValue("#emp_contact", tbContact.Text);
cmd1.Parameters.AddWithValue("#emp_dob", Convert.ToDateTime(dtpBirth.Value.ToString()));
cmd1.Parameters.AddWithValue("#emp_bloodgroup", cBoxBloodGroup.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_maritialstatus", cBoxMaritialStatus.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("#emp_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#emp_per_address", tbPerAddress.Text);
cmd1.Parameters.AddWithValue("#emp_picture", SaveImage());
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Has been Updated Successfully !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGridView();
ResetForm();
tbName.Focus();
}
}
}
//}
//else
//{
// MessageBox.Show("All Fields are Mandatory !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// tbName.Focus();
//}
}
catch (Exception)
{
throw;
}
}
Here is the Method for for Loading data to gridview
private void FillGridView()
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT * FROM EMP_Master", con))
{
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
}
}
}
Is there's something wrong with my code ? i guess not because data is inserted and updated in to the database . help me please
You need to fill your grid view with data. And I think you should add binding in FillGridView() method:
private void FillGridView()
{
CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT * FROM EMP_Master", con))
{
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
gridView.DataSource = dt;
gridView.Update();
}
}
}
Related
Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.
How do I insert that data into the database based on what the user selects?
You can try this,
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into sample values(#payment)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#payment", payment.SelectedValue);
if (cn.State == ConnectionState.Closed)
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
lblmsg.Text = "Data entered successfully!!!";
}
I found the answer to my own question if someone needs it
try
{
var connection = getConnection();
connection.Open();
if (CashRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succsefully picked type");
}
else
{
MessageBox.Show("error");
}
}
else if (CardRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succesfully picked type");
}
else
{
MessageBox.Show("Error");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Luka,
Try it below.
Add HTML Markup like:
<asp:CheckBox ID="chkCash" runat="server" />
.cs file add below code.
string Cash = chkCash.Checked ? "Y" : "N";
And send or add value like.
SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(#Cash)"))
{
cmd.Parameters.AddWithValue("#Cash", Cash);
}
I am writing a program to add information from a Form into my database, however, when running the program I am met with the following syntax error:
System.InvalidOperationException: 'Invalid attempt to call Read when reader is closed.'
If I don't close the reader the statement sqlCmd.ExecuteNonQuery(); will not be run as there is already an open DataReader associated with this Command.
Here is the source:
string isbnQuery = "SELECT * FROM book WHERE isbn = '" + txtbox_id.Text + "'";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmdQuery = new SqlCommand(isbnQuery, sqlCon);
SqlDataAdapter sda = new SqlDataAdapter(isbnQuery, sqlCon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
try
{
using (sqlCon)
{
sqlCon.Open();
SqlDataReader reader = sqlCmdQuery.ExecuteReader();
while (reader.Read())
{
DialogResult dr = MessageBox.Show("Is this Correct?", reader["title"].ToString(), MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
SqlCommand sqlCmd = new SqlCommand("book_log", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
// adding text-field data to the database
char current = 'N';
sqlCmd.Parameters.AddWithValue("#book_id", reader["book_id"]);
sqlCmd.Parameters.AddWithValue("#id", ID.getID);
sqlCmd.Parameters.AddWithValue("#date_from", dtp_from.Value.ToString());
sqlCmd.Parameters.AddWithValue("#date_to", dtp_hand.Value.ToString());
sqlCmd.Parameters.AddWithValue("#fine", current);
sqlCmd.Parameters.AddWithValue("#handed", current);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Done!");
}
else if (dr == DialogResult.No)
{
return;
}
}
}
}
catch (SqlException ex)
{
MessageBox.Show("Contact a Staff Member " + ex.Message);
}
finally
{
sqlCon.Close();
}
}
else
{
Console.WriteLine("Book Not Found");
}
}
I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.
im doing an update statement where the datetimepicker(logout) will insert into the same row as login but its making another row when i logout here is the link : http://imgur.com/a/rAWhi
ps. the problem here is the logout button is inserting into another row.. but i want to insert it in the same row.
here is my code :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from empinfo where username = '" + label4.Text + "' and IDNUMBER = '" + textBox1.Text + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Input your id number");
}
else if (i == 0)
{
MessageBox.Show("Username and IDNUMBER didn't match.", "Log-In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateuser();
login frmm = new login();
frmm.Show();
this.Close();
}
con.Close();
}
public void updateuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmdupdate;
cnn.Open();
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout = #logout";
cmdupdate.CommandText = "Insert into employee (logout) values (#logout)";
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
As #Ben in the comments pointed out, you do not need to use insert and only want update so change your code like this:
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout=#logout";
cmdupdate.CommandText += "WHERE IDNUMBER=#IDNUMBER";
cmdupdate.Parameters.AddWithValue("#IDNUMBER", textBox1.Text.Trim());
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
The Where is to make sure it only updates the IDNUMBER on the textbox.
I think you should create different methods for login and logout like
For LOGIN
public static long id;
public void loginuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into employee (logout) values (#logout)";
cmd.Parameters.AddWithValue("#login", DateTime.Now);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId; // it will return the id of last inserted row
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
For LOGOUT
public void logoutuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "update employee set logout = #logout WHERE IDNUMBER=#ID";
cmd.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
I have searched a lot and failed to and finally arrived here...
I am creating a checkboxList dynamically from the database successfully. Then I want to submit these selcted checked items, I am unable to access. Please find the code....
protected void CreateCheckBoxListDynamically()
{
DataTable dt = new DataTable();
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_GetDomesticCountryList", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
if (ddlTournamentType.SelectedValue != "Select" && ddlTournamentType.SelectedValue != "")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList cblCountry = new CheckBoxList();
cblCountry.ID = "cblCountryTeam";
cblCountry.DataTextField = dt.Columns["CT_CountryTeamName"].ToString();
cblCountry.DataValueField = dt.Columns["CT_CountryTeamId"].ToString();
cblCountry.DataSource = dt;
cblCountry.DataBind();
//phCheckBoxList.Attributes.Add("class", "groupbox");
phCheckBoxList.Controls.Add(cblCountry);
phCheckBoxList.Controls.Add(new LiteralControl("<br />"));
}
dBConnection.Close();
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
// Close data reader object and database connection
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = null;
SqlConnection dBConnection = new SqlConnection();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
string countryTeamIds = "";
try
{
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
cmd = new SqlCommand("SP_AddNewSeries", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#MemberId", SqlDbType.Int).Value = memberId;
if (ddlTournamentType.SelectedValue != "Select")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesStartDate.Text))
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesStartDate.Text);
else
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesEndDate.Text))
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesEndDate.Text);
else
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = DBNull.Value;
// get values from dynamic controls
CheckBoxList cb = (CheckBoxList)phCheckBoxList.FindControl("cblCountryTeam");
if (cb != null)
{
foreach (ListItem li in cb.Items)
{
if (li.Selected)
countryTeamIds += li.Value + "~";
}
}
if (!string.IsNullOrEmpty(countryTeamIds))
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = countryTeamIds;
else
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
int i = cmd.ExecuteNonQuery();
//hdnseriesId.Value = cmd.Parameters["#SeriesId"].Value.ToString();
if (i == 0)
{
msgNoRecords.Visible = true;
}
else
{
msgNoRecords.Visible = false;
//Response.Redirect("~/country.aspx", false);
}
dBConnection.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
As per you code details object phCheckBoxList has created in aspx page.
If i am right then this will create problem adding checkboxs at server side.
why dont you create only checkbox at server side rather than checkboxLIST.
After creating checkbox you can add is <div>(this has to be declared at aspx page). this <div> should have an ID and make it runat="server" so you can get this.
After doing above task you can easy find every checkbox from that div at server side code.