checkBox in gridView doesn't update my table - c#

I am using the following the code to populate table on clicking upon the checkbox but there is no change in table
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkUpdate = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
cmd .ExecuteNonQuery ();
}
}
}
}

Try this code it works
foreach (GridViewRows gdrv in GridView1.Rows)
{
CheckBox chkUpdate = (CheckBox)
gdrv.FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = gdrv.Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
con.open();
cmd .ExecuteNonQuery ();
con.close();
}
}
}

I'm guessing you really don't have a space in cmd .ExecuteNonQuery ();
When debugging, can you step into the if(chkUpdate.Checked) block?

I think the only problem in the query is the "Where" condition... if the p_id is Int type then you don't have to use ''...
So the statement must be :
string str1 = "update app1 set p_id=0 where p_id=" + strID;

Related

C# Update command with oledb

I'm trying to update the selected row in access database. How do I Update selected row in my access database?
I've tried using the update command
private void btnCancel_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dataRes.Rows.Count; i++)
{
string a = "Cancelled";
DataGridViewRow dr = dataRes.Rows[i];
if (dr.Selected == true)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Reservation SET Status ='" + a + "' WHERE ID = " + i +" ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Reservation Cancelled");
}
}
}

My delete function is not removing entries and is being ignored

I am having problems getting my delete function to work in my ASP.net (C#) web application and I really have no idea where to go next.
The function is called on button clicked but it is as if the Page_Load method is completely ignoring the command. I'm new to this and would appreciate some help.
Thanks.
Here is the Page_load, the DisplayData method, the Count method and the delete method which is called from a button click.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection cn;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
protected void displayData()
{
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++)
reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
protected void deleteData()
{
var cmd = cn.CreateCommand();
string query = "DELETE FROM [Footballer] WHERE [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}
From the code, it looks like Textbox4 value is getting overwritten before the Delete, Page_load will get called for each postback including button click event. The flag bool firstTime = true doesn't work for the purpose you are trying to achieve. I believe you want to load text box data only when the page loads first time. so you should modify the Page_load event to use IsPostBack property instead of firstTime flag, like below.
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if(!IsPostBack)
{
displayData();
}
}
This will ensure that, TextBox4 value entered by you in UI won't get overwritten when you click delete button and delete code should work as expected
Don't open the connection in Page_Load only open it where needed. Also use using to properly dispose of your resources.
public partial class WebForm1 : System.Web.UI.Page
{
//You should really pull this from your web.config
string connectionString = "(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
}
}
protected void displayData()
{
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++) reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
}
}
protected void deleteData()
{
//Add A break point here to ensure the method is hit
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
string query = "DELETE from [Footballer] where [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
//When stepping through in debug mode, make sure
//name is what you expect.
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}
}
Note, I've done all this in the SO editor so I may have missed some closing }

update selected data in mysql in c#

how to update selected data in mysql in c#?
this is my code when i press button2 . all data "jumlah_product" minus two.
i want to make just minus two "jumlah_product" in selected data.
private void button2_Click_1(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost;Database=maindata;Uid=root;pwd=firmandoang;";
string Query = "select * from maindata.product_database where idproduct = '" + this.textBox1.Text + "' OR namaproduct LIKE '" + this.textBox1.Text + "'";
MySqlConnection conn = new MySqlConnection(MyConnectionString);
MySqlCommand command = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
myReader = command.ExecuteReader();
try
{
if (myReader.Read())
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[1].Value = myReader.GetString("namaproduct");
row.Cells[2].Value = myReader.GetString("hargaproduct");
int count = Convert.ToInt32(textBox2.Text);
int price = Convert.ToInt32(row.Cells[2].Value);
row.Cells[3].Value = count;
row.Cells[4].Value = price *= count;
dataGridView1.Rows.Add(row);
string update = "UPDATE maindata.product_database SET jumlah_product=(jumlah_product - '" + count + "')";
MySqlCommand cmd = new MySqlCommand(update, conn);
MySqlDataReader reader;
myReader.Close();
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
}
else
{
MessageBox.Show("No Data ");
}
sorry for bad english . I hope you understand :)

Not able to get value from drop down list, c#

In page load I'm loading a drop down list with names from a postgreSQL database, using SQL.
Later in the code I want to save the selected value in the drop down list into a string variable.
That won't happen. What happens is the first value in the list (index 0) always saves, no matter of which I have selected.
Heres is page load (works fine):
protected void Page_Load(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
Here is Button1_Click. I want to save the selected value into string variable syv.
protected void Button1_Click(object sender, EventArgs e)
{
string syv = ddPersons.SelectedItem.Text;
string name = txtName.Text;
int studentid = 0;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sSYS;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT id FROM tbl_student WHERE name = '" + name + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
studentid = (int)dr["id"];
}
}
I have tried
string syv = ddPersons.SelectedItem.Text;
string syv = ddPersons.SelectedItem.Value;
string syv = ddPersons.Text;
string syv = ddPersons.SelectedValue;
It might be that ViewState is saving the state of your page. Why don't you include the following line in your Page_Load method:
if ( !IsPostBack)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
It will prevent the Page_Load to populate duplicate items every time someone clicks on the button and prevents the ViewState to interfere with the state of your controls.

Inserting selected data using checkbox from gridview

When I select the in the gridview using checkbox, I want it to insert the data into the database, but it is not adding it. My code is below, please see where I am going wrong.
public partial class HomeTeamCheckList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LiveGameReporting Window
SubmitLineUp.Attributes.Add("onclick", "PassValues();");
SubmitLineUp.Text = "Submit " + Session["HomeTeam"] + "'s Line Up";
}
protected void SubmitLineUp_Click(object sender, EventArgs e)
{
String GameID = string.Empty;
String Name = string.Empty;
String Number = string.Empty;
int GKGVCount = GoalKeeperGridView.Rows.Count;
foreach (GridViewRow gkrow in GoalKeeperGridView.Rows)
{
GameID = (String)Session["GameID"];
Number = gkrow.Cells[0].Text;
Name = gkrow.Cells[1].Text;
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
}
}
}
Two thoughts:
Use a try-catch to see if you're getting any SQL errors.
Check the return value of the cmd.ExecuteNonQuery(); to see if any rows were actually affected / inserted.
Like this:
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
// use a debugger to see if any rows were actually affected / inserted
int rowsAffected = cmd.ExecuteNonQuery();
}
catch(SQLException error)
{
// Use a debugger to see if you are getting an error on execution
string errorText = error.message;
}
Your query string looks ok, so it could be a permissions error. But the steps above will help you track it down.

Categories

Resources