Increment Column Value in database using c# asp.net - c#

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

Related

Update query updates all records except the name

I am stuck with an issue with updating. When I open my Windows form developed in C# using SQL, the update updates all fields but not the name. Could you tell me what I did wrong?
Here is my code
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + tbBpname.Text + "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
You are updating the Name where the Name equals tbBpname.Text so it will not change the name for row you are updating.
private string originalName;
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
originalName = dr["Name"].ToString()
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + originalName+ "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
Please note you should use SqlParameters and not build the query as a string.

Deleting mysql table entry with 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.

Edit Not Working After GridView Filter By Drop Down

I am stuck at editing editing point after filtering the GridView By a drop down list(i.e dropdown is placed outside the gridview).
When I click on editlink after filtering the gridview it makes the starting rows of the whole grid editable.
I want to do this in ASP.NET instead of J-Query Or Ajax.!
Any One , Please Help me on this???
Here is my code:`
protected void FillGrid()
{
//String StudentSectionID = Convert.ToString(ddlsectionid.SelectedValue);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
con.Open();
string query = " SELECT St.StudentID, StudentNo, StudentPassword, StudentName, Cl.StudentClassName, Cl.StudentClassID,Se.StudentSectionID,Ge.StudentGenderID,Gu.StudentGuardianID,Tr.StudentTransportID,Se.StudentSectionName, StudentRollno, StudentSession, Ge.StudentGenderName, StudentPhone,StudentAddress, StudentEmail, Gu.StudentGuardianName, StudentReligion,Tr.StudentTransportRouteNo, StudentDOB,StudentFees from Student St Inner join Class Cl ON St.StudentClassID = Cl.StudentClassID Inner Join Section Se ON St.StudentSectionID = Se.StudentSectionID Inner Join Gender Ge ON Ge.StudentGenderID = St.StudentGenderID Inner Join Guardian Gu ON Gu.StudentGuardianID = St.StudentGuardianID Inner Join Transport Tr ON Tr.StudentTransportID = St.StudentTransportID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv_student.DataSource = ds;
gv_student.DataBind();
}
protected void ddlsectionid_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentSectionName = Convert.ToString(ddlsectionid.SelectedItem);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand("SELECT St.StudentID,StudentNo,StudentPassword, StudentName, Cl.StudentClassName, Se.StudentSectionName,Se.StudentSectionID, StudentRollno, StudentSession, Ge.StudentGenderName, StudentPhone, StudentAddress, StudentEmail, Gu.StudentGuardianName, StudentReligion, Tr.StudentTransportRouteNo, StudentDOB,StudentFees from Student St Inner join Class Cl ON St.StudentClassID = Cl.StudentClassID Inner Join Section Se ON St.StudentSectionID = Se.StudentSectionID Inner Join Gender Ge ON Ge.StudentGenderID = St.StudentGenderID Inner Join Guardian Gu ON Gu.StudentGuardianID = St.StudentGuardianID Inner Join Transport Tr ON Tr.StudentTransportID = St.StudentTransportID where Se.StudentSectionName='"+StudentSectionName+"'", oconn);
SqlDataAdapter oda = new SqlDataAdapter(ocmd);
SqlCommandBuilder builder = new SqlCommandBuilder(oda);
DataSet ds = new DataSet();
oda.Fill(ds);
gv_student.DataSource = ds;
gv_student.DataBind();
}
protected void gv_student_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlclassid = (DropDownList)e.Row.FindControl("ddlclassid");
DataTable dt;
string SQL = "SELECT * FROM Class";
string sConstr = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
}
}
ddlclassid.DataSource = dt;
ddlclassid.DataTextField = "StudentClassName";
ddlclassid.DataValueField = "StudentClassID";
ddlclassid.DataBind();
ddlclassid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentClassID"].ToString();
}
}
// For Section
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlsectionid = (DropDownList)e.Row.FindControl("ddlsectionid");
DataTable dt1;
string SQL1 = "SELECT * FROM Section";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL1, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt1 = new DataTable("tbl");
da.Fill(dt1);
}
}
}
ddlsectionid.DataSource = dt1;
ddlsectionid.DataTextField = "StudentSectionName";
ddlsectionid.DataValueField = "StudentSectionID";
ddlsectionid.DataBind();
ddlsectionid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentSectionID"].ToString();
}
}
//For Gender
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlgenderid = (DropDownList)e.Row.FindControl("ddlgenderid");
DataTable dt2;
string SQL2 = "SELECT * FROM Gender";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL2, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt2 = new DataTable("tbl");
da.Fill(dt2);
}
}
}
ddlgenderid.DataSource = dt2;
ddlgenderid.DataTextField = "StudentGenderName";
ddlgenderid.DataValueField = "StudentGenderID";
ddlgenderid.DataBind();
ddlgenderid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentGenderID"].ToString();
}
}
//For Guardian
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlguardianid = (DropDownList)e.Row.FindControl("ddlguardianid");
DataTable dt3;
string SQL3 = "SELECT * FROM Guardian";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL3, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt3 = new DataTable("tbl");
da.Fill(dt3);
}
}
}
ddlguardianid.DataSource = dt3;
ddlguardianid.DataTextField = "StudentGuardianName";
ddlguardianid.DataValueField = "StudentGuardianID";
ddlguardianid.DataBind();
ddlguardianid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentGuardianID"].ToString();
}
}
//For Transport
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddltransportid = (DropDownList)e.Row.FindControl("ddltransportid");
DataTable dt4;
string SQL4 = "SELECT * FROM Transport";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL4, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt4 = new DataTable("tbl");
da.Fill(dt4);
}
}
}
ddltransportid.DataSource = dt4;
ddltransportid.DataTextField = "StudentTransportRouteNo";
ddltransportid.DataValueField = "StudentTransportID";
ddltransportid.DataBind();
ddltransportid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentTransportID"].ToString();
}
}
}
protected void gv_student_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int StudentID = Convert.ToInt32(gv_student.DataKeys[e.RowIndex].Value);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand();
ocmd.CommandText = "DELETE FROM Student WHERE StudentID=#StudentID";
ocmd.Parameters.AddWithValue("#StudentID", StudentID);
ocmd.Connection = oconn;
ocmd.ExecuteNonQuery();
oconn.Close();
FillGrid();
}
protected void gv_student_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_student.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void gv_student_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int StudentID = int.Parse(((Label)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("lbl_ID"))).Text);
string StudentNo = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtno"))).Text;
string StudentPassword = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtpassword"))).Text;
string StudentName = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtname"))).Text;
string StudentRollno = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtrollno"))).Text;
string StudentSession = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtsession"))).Text;
string StudentPhone = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtphone"))).Text;
string StudentAddress = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtaddress"))).Text;
string StudentEmail = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtemail"))).Text;
string StudentReligion = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtreligion"))).Text;
string StudentDOB = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtdob"))).Text;
string StudentFees = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtfees"))).Text;
int StudentClassID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlclassid"))).SelectedValue);
int StudentSectionID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].FindControl("ddlsectionid"))).SelectedValue);
int StudentGenderID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlgenderid"))).SelectedValue);
int StudentGuardianID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlguardianid"))).SelectedValue);
int StudentTransportID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddltransportid"))).SelectedValue);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand();
ocmd.CommandText = "UPDATE Student SET StudentNo=#StudentNo, StudentPassword=#StudentPassword, StudentName=#StudentName,StudentRollno=#StudentRollno,StudentSession=#StudentSession,StudentPhone=#StudentPhone,StudentAddress=#StudentAddress,StudentEmail=#StudentEmail,StudentReligion=#StudentReligion,StudentDOB=#StudentDOB,StudentFees=#StudentFees,StudentTransportID=#StudentTransportID,StudentGuardianID=#StudentGuardianID,StudentGenderID=#StudentGenderID,StudentSectionID=#StudentSectionID,StudentClassID=#StudentClassID WHERE StudentID=#StudentID";
ocmd.Parameters.AddWithValue("#StudentID", StudentID);
ocmd.Parameters.AddWithValue("#StudentClassID", StudentClassID);
ocmd.Parameters.AddWithValue("#StudentSectionID", StudentSectionID);
ocmd.Parameters.AddWithValue("#StudentGenderID", StudentGenderID);
ocmd.Parameters.AddWithValue("#StudentGuardianID", StudentGuardianID);
ocmd.Parameters.AddWithValue("#StudentTransportID", StudentTransportID);
ocmd.Parameters.AddWithValue("#StudentFees", StudentFees);
ocmd.Parameters.AddWithValue("#StudentDOB", StudentDOB);
ocmd.Parameters.AddWithValue("#StudentReligion", StudentReligion);
ocmd.Parameters.AddWithValue("#StudentEmail", StudentEmail);
ocmd.Parameters.AddWithValue("#StudentAddress", StudentAddress);
ocmd.Parameters.AddWithValue("#StudentPhone", StudentPhone);
ocmd.Parameters.AddWithValue("#StudentSession", StudentSession);
ocmd.Parameters.AddWithValue("#StudentRollno", StudentRollno);
ocmd.Parameters.AddWithValue("#StudentName", StudentName);
ocmd.Parameters.AddWithValue("#StudentPassword", StudentPassword);
ocmd.Parameters.AddWithValue("#StudentNo", StudentNo);
ocmd.Connection = oconn;
ocmd.ExecuteNonQuery();
gv_student.EditIndex = -1;
FillGrid();
oconn.Close();
}
protected void gv_student_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_student.EditIndex = -1;
FillGrid();
}

Add validation on GridView row in ASP.NET

i dont have an edit template. is it possible for me to add validations on my text box in grid view during edit mode?
It updates the edited fields and works fine, but when I type in special characters, it is still being accepted. How can I validate those editableTextBoxes and prevent the user from entering invalid input?
UPDATE
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
GetProducts(0);
}
fields not updating
UPDATE getproducts(0)
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = k.GetAllProducts();
gdview.DataBind();
}
datatable:
public DataTable GetAllProducts()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 20);
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("SP_GetAllProducts", parameters);
return dt;
}
UPDATE:
Current Code:
protected void gdview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprodname) && regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
}
GetProducts(0);
}
var regex_valid_price = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
var regex_no_special_chars = new Regex(#"^[a-zA-Z0-9 ]*$");
if(regex_no_special_chars.IsMatch(strprodname) && regex_valid_price.IsMatch(strprice)){
// do your db inserts
}
Visit http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/validation/defaultcs.aspx
you may get the solution.

why it get old dataset

My program is working normally when I select a listbox item.it getting datas correct dataset and correctly.when I write to textbox,my source method working and finding right results.but after when I selected listbox item it bringing old dataset datas to screen.What can I do in this methods?
public void ara(string str, int neyegore)
{
sqlcon.Open();
if (neyegore == 0)
komut = new SqlCommand("select * from FilmTablo WHERE ad LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 1)
komut = new SqlCommand("select * from FilmTablo WHERE tur LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 2)
komut = new SqlCommand("select * from FilmTablo WHERE yonetmen LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 3)
komut = new SqlCommand("select * from FilmTablo WHERE oyuncular LIKE '%" + str + "%'", sqlcon);
sdr = null;
sdr = komut.ExecuteReader();
dt2 = new DataTable();
dt2.Load(sdr);
ds2 = new DataSet();
ds2.Tables.Add(dt2);
listBox1.Items.Clear();
// sayac2 = 1;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
listBox1.Items.Add(ds2.Tables[0].Rows[i].ItemArray[0]);
i++;
}
sqlcon.Close();
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
txtad.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[0].ToString().Trim();
txttur.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[1].ToString().Trim();
txtsure.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[2].ToString().Trim();
txtyonetmen.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[3].ToString().Trim();
txtoyuncular.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[4].ToString().Trim();
txtsenaryo.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[5].ToString().Trim();
byte[] resim = (byte[])ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[7];
image1.Source = GetBitmapImage(resim);
}
public void listeyiguncelle()
{
sqlcon.Open();
komut = new SqlCommand("select * from FilmTablo", sqlcon);
sdr = null;
sdr = komut.ExecuteReader();
dt = new DataTable();
dt.Load(sdr);
ds = new FilmDataDataSet();
ds.Tables.Add(dt);
listBox1.Items.Clear();
int i = 0;
//MessageBox.Show(ds.Tables[1].Rows.Count.ToString());
while (i < ds.Tables[1].Rows.Count)
{
listBox1.Items.Add(ds.Tables[1].Rows[i].ItemArray[0]);
i++;
}
sqlcon.Close();
lblfilmsayisi.Content = ds.Tables[1].Rows.Count;
}

Categories

Resources