Add validation on GridView row in ASP.NET - c#

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.

Related

How to display gridview by using a table as condition then using select query to do the filter

I am new of the C# asp.net.
I have two tables. The first can be a setup table then second one is a table that wants to do a filter. I want use the setup table as the condition to search the second table then filter the result and display as gridview.
As example, the setup table got "S","50","BU2". then they will be condition to search the second table by using Select query
protected void Run_Click(object sender, EventArgs e)
{
try
{
string site = string.Empty;
string operation = string.Empty;
string bu = string.Empty;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
using (SqlConnection conn = new SqlConnection(Contest))
{
string query = string.Empty;
conn.Open();
query = "Select Site, Operation, BU from [dbo].[Sampling_test]";
SqlDataAdapter adp = new SqlDataAdapter(query, conn);
adp.Fill(dt);
}
for (int b = 0; b < dt.Rows.Count; b++)
{
site = dt.Rows[b]["Site"].ToString();
operation = dt.Rows[b]["Operation"].ToString();
bu = dt.Rows[b]["BU"].ToString();
string[] operationArray = operation.Split(',');
string operationQuery = string.Empty;
for (int a = 0; a < operationArray.Length; a++)
{
operationQuery = operationQuery + "" + operationArray[a] + ",";
}
operationQuery.TrimEnd(',');
using (SqlConnection conn = new SqlConnection(Contest))
{
string query = string.Empty;
conn.Open();
query = "Select * from [dbo].[JHtest] where Site = '" +site+ "' AND Operation in ('" +operationQuery+ "') AND BU = '" +bu+ "' ";
SqlDataAdapter adp = new SqlDataAdapter(query, conn);
adp.Fill(dt1);
}
//insert dt into database
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
conn.Open();
GridView2.DataSource = dt1;
GridView2.DataBind();
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}

Session inside datatable in c#.net

In the below code ,
Session["FirstName"] = SCode.ToString(); is having error (the name session does not exist in current context).thanks
public DataTable Searchup(string SiteCode = "", string EmployeeRole = "")
{
DbConnection conn = _dataFactory.CreateConnection();
DbDataAdapter da = _dataFactory.CreateDataAdapter();
DataTable dt = null;
try
{
conn.ConnectionString = _connectionString;
conn.Open();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandType = CommandType.Text;
DbParameter param = null;
string sql = "SELECT ID,SITECODE,EMPLOYEEROLE,EMPLOYEEID, FROM " + _tblnpf + "User WHERE Empl <> 'Admin' ";
if (!String.IsNullOrEmpty(SiteCode.Trim()))
{
sql += "AND SiteCode = #SiteCode ";
OracleHelper.CreateParameter(ref da, ref param, "#SiteCode", DbType.String, ParameterDirection.Input, SiteCode);
Session["FirstName"] = SCode.ToString();
}
da.SelectCommand.CommandText = OracleHelper.FixCommandText(sql);
DataTable dt1 = new DataTable("User");
da.Fill(dt1);

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.

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