Deleting mysql table entry with C# - c#

Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.

Related

Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)

I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());

How to make dependent combo boxes work correctly

I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!

aspx c#. 2x textbox on site don't work

I have two textboxes and two buttons on one site. The problem is that this second textbox and second button doesn't work. First textbox+button doing well:
int NoOfDigTextBoxEngine;
protected void TextBoxADDEngine_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxEngine = TextBoxADDEngine.Text.Length;
}
protected void ButtonADDEngine_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Engine, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsEngine";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxEngine == 7)
{
try
{
Convert.ToInt32(TextBoxADDEngine.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsEngine ([Engine], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDEngine.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView3.DataBind();
TextBoxADDEngine.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika może zawierać jedynie cyfry.')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika musi mieć 7 cyfr.Podano: " + NoOfDigTextBoxEngine + " ')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
}
}
But the second (is the same) don't want to work.
int NoOfDigTextBoxGear;
protected void TextBoxADDGear_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxGear = TextBoxADDGear.Text.Length;
}
protected void ButtonADDGear_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Gear, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsGear";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxGear == 7)
{
try
{
Convert.ToInt32(TextBoxADDGear.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsGear ([Gear], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDGear.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView5.DataBind();
TextBoxADDGear.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni może zawierać jedynie cyfry.')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni musi mieć 7 cyfr. Podano: "+ NoOfDigTextBoxGear +" ')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
}
}
When i write something in second textbox and then click button- always NoOfDigTextBoxGear = 0...why?
It's not make any sense for me because this code(for second textbox and button) is the same like the the first one(for first textbox and button).
Oh... i just saw this:
<asp:TextBox ID="TextBoxADDGear" runat="server" Visible="False"
Width="96px"></asp:TextBox>
I didn't add ontextchanged(!)
ontextchanged="TextBoxADDGear_TextChanged"
Now everything is ok.

How to set dateTimePickerValue to null or empty in c#

I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";

Increment Column Value in database using c# asp.net

How to increase totaldownloads value in my database file code is given below
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
lblMessage.Visible = true;
GridView1.Visible = false;
//AppContent.Visible = false;
}
else
{
if (!Page.IsPostBack)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
//Add some column to datatable display some products
dt.Columns.Add("appImg");
dt.Columns.Add("appName");
dt.Columns.Add("appLink");
dt.Columns.Add("appType");
dt.Columns.Add("TotalVisitors");
dt.Columns.Add("TotalDownloads");
dt.Columns.Add("RemainingVisitors");
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["appImg"] = ((DataRow)row)["AppImg"].ToString();
dr["appName"] = ((DataRow)row)["AppName"].ToString();
dr["appLink"] = ((DataRow)row)["AppLink"].ToString();
dr["appType"] = ((DataRow)row)["AppType"].ToString();
dr["TotalVisitors"] = "Plan Visitors: " + ((DataRow)row)["TotalVisitors"].ToString();
dr["TotalDownloads"] = "Downloaded: " + ((DataRow)row)["TotalDownloads"].ToString();
dr["RemainingVisitors"] = "Remaining Visitors: " + ((DataRow)row)["RemainingVisitors"].ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
public ArrayList ConvertDataSetToArrayList()
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand cmd = new SqlCommand();
if (Session["UserId"] != null && (Session["UserTypeId"] != null && Convert.ToInt32(Session["UserTypeId"]) != 2))
{
cmd.CommandText = "Select * from tblApp WHERE AppType = '" + Session["UserOSType"] + "' ORDER BY TotalVisitors";
}
else
{
cmd.CommandText = "Select * from tblApp ORDER BY TotalVisitors";
}
cmd.Connection = sqlcon;
sqlcon.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet dsApp = new DataSet();
da.Fill(dsApp, "tblApp");
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in dsApp.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
sqlcon.Close();
return myArrayList;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "download")
{
Button ib = (Button)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label l2 = (Label)row.FindControl("Label2");
Label lbTotallVisitors = (Label)row.FindControl("Label4");
Label lblTotalDownloads = (Label)row.FindControl("Label5");
Label lblRemainingVisitors = (Label)row.FindControl("Label6");
string updateSQL = "UPDATE tblUser SET DownloadedApps = '" + lbl + "', Amount = '" + Session["Amount"] + "', TotalAmount='" + Session["TotalAmount"] + "' WHERE Id= '" + Session["UserId"] + "'";
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()))
{
using (SqlCommand updateCommand = new SqlCommand(updateSQL, sqlConn))
{
sqlConn.Open();
updateCommand.ExecuteNonQuery();
updateCommand.Connection.Close();
}
}
Response.Redirect(l2.Text);
}
}
UPDATE Table SET Column = Column + 1

Categories

Resources