asp.net vallidation on database save button - c#

I use a button to save textbox en dropdown valves to a database
but the problem is its for a reservation system for my cousin and he has a maximum of 50 seats.
My question is can i put in some kind of validation or count that give back a massage when the
maxiumum places is reached or surpased to the one that wants to make a reservation.
here is my button
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BT-1ConnectionString"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from OpdrachtGever";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "OpdrachtGever");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
drow["Naam"] = TextBox1.Text;
drow["Adres"] = TextBox2.Text;
drow["PostCode"] = TextBox3.Text;
drow["WoonPlaats"] = TextBox4.Text;
drow["TelefoonNummer"] = TextBox5.Text;
drow["EmailAdres"] = TextBox6.Text;
drow["AantalPersonen"] = DropDownList1.SelectedValue;
ds.Tables["OpdrachtGever"].Rows.Add(drow);
da.Update(ds, "OpdrachtGever");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
}
}
}

You could check the number of rows in the OpdrachtGever table after filling the dataset:
da.Fill(ds, "OpdrachtGever");
// Check booked count
int totalBooked = 0;
foreach (DataRow row in ds.Tables["OpdrachtGever"].Rows)
{
totalBooked += Int32.Parse(row["AantalPersonen"]);
}
if (totalBooked >= 50)
{
//show error and return
}

Related

in C# Selecting Urdu text from Combo box not updating Text box or Label in form but works well with English text with same code

I am creating a software on C# with SQL server management with database tables in Urdu text. Having a problem: I made a table TblMardanax with three columns sm_id, sm_sympton and sm_tehreek in SQL. on C# windows form one combo box to display sm_symptom and a label with combo to display sm_tehreek. It does well (changes label text according to the selected item from combo) when I put data in english in the table TblMardanax but when I put data in Urdu it keeps blank (unchanged) the label. I do not understand what is the problem and there is no error showing in the code. The codes are here.
private void Symptoms_Load(object sender, EventArgs e)
{
MardanaCB.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT sm_symptom FROM TblMardanax";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
MardanaCB.Items.Add(dr["sm_symptom"].ToString());
}
con.Close();
}
private void MardanaCB_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM TblMardanax WHERE sm_symptom='" + MardanaCB.Items[MardanaCB.SelectedIndex].ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
SymLbl1.Text = dr["sm_tehreek"].ToString();
SymTxt1.Text = dr["sm_tehreek"].ToString();
}
con.Close();
}
Al-Hamdo-Lillah, my problem is solved:here is the code which works fine for Urdu like languages to add in SQL database via c#.
private void MardanaCB_SelectedIndexChanged(object sender, EventArgs e)
{
if (MardanaCB.Text =="")
{
SymLbl1.Text = "0";
}
else
{
SymLbl1.Text = MardanaCB.SelectedValue.ToString();
//con.Open();
//SqlCommand cmd = con.CreateCommand();
//cmd.CommandType = CommandType.Text;
//cmd.CommandText = "SELECT * FROM Alamaat WHERE al_name=(N'" + MardanaCB.SelectedItem.ToString() + "')";//this is the line with N worked fine.
//DataTable dt = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.Fill(dt);
//foreach (DataRow dr in dt.Rows)
//{
//SymLbl1.Text = dr["al_tehreek"].ToString();
//}
//con.Close();
SymplusCB1.Enabled = true;
}
}

create at run time multiple text box and assign value textbox from database..i want to show all the data from database

How can i create at run time multiple text box and assign value to textbox from database..i want to show all the data from database. For example if i have store 4 rows then program should show all 4 rows in dynamically created text boxes at once. C# window form give me code or example thanks..
int txtno = int.Parse(textBox1.Text);
try
{
string MyConnection2 = "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True";
//Display query
string Query = "select * from test123.task;";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
// MyConn2.Open();
//For offline connection we weill use MySqlDataAdapter class.
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataSet ds = new DataSet();
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
MyAdapter.Fill(ds);
// MySqlDataReader MyReader2;
foreach (DataRow de in DataSet.TABLe.Row)
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
if (MyReader2.Read())
{
string val = MyReader2[0].ToString();
if (val == "")
{
//textBox1.Text = ()
}
else
{
txtno = Convert.ToInt32(MyReader2[0].ToString());
txtno = txtno + 1;
TextBox txt = new TextBox();
// txtno.Text = (i + 1).ToString()
panel2.Controls.Add(txt);
panel2.Show();
textBox1.Text = txtno.ToString();
}
}
//for (int i = 0; i < txtno; i++)
//{
// Label lbl = new Label();
// lbl.Text = (MyReader2["task_comment"].ToString());
// // lbl = "Label" + i.ToString();
// panel2.Controls.Add(lbl);
//}
MyConn2.Close();//Connection closed here
}
catch (Exception ex)
{
}
There are lots of better ways of programing what you want but I provide a simple way to fix your code by specifying the Top and Left of your Textboxes :
MySqlConnection con = new SqlConnection( "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True");
MySqlCommand cmd = new SqlCommand( "select * from test123.task;", con);
con.open();
MySqlDataReader dr= cmd.ExecuteReader();
int top=100;
While(dr.read())
{
Textbox textBox= new TextBox();
panel2.Controls.Add(textBox);
textBox.Text=dr[0 /* or instead of 0 use your fieldName */].ToString();
textBox.Left=150;
textBox.Top=top;
top+=100;
}
con.close()

da=Fill(ds); error near '=' in asp.net

This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.

How to show Data in table?

I am a beginner in C# and using MS Visual Studio 2010. Ans my problem is I am inserting data through textbox in a table named as (tbl_employees) and saving it successfully.
After saving when I see the table the new inserted data is not showing in tbl_employee even after updating.
Here is my code for updating table
private void btnupdate_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tbl_employees";
da = new System.Data.SqlClient.SqlDataAdapter(sql , conString);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow row = ds.Tables[0].Rows[inc];
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
MessageBox.Show("Now Table is updated too. . . ");
}
Code with ease to understand and implement
Insert
private void Insert()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Insert into YourTable Select (#Val1,#Val2,#Val3)";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Update
private void Update()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Update YourTable Set Field1=#Val1,Field2=#Val2,Field3=#Val3 Where YourPrimaryKey=#Key";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
command.Parameters.Add("#Key",txt4.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Select
private DataTable Get()
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Select * From YourTable";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
using(var reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
{
dt.Load(reader);
}
con.Close();
}
}
return dt;
}
So now you have a Get method that returns DataTable , now you need a grid to display that data. Quite simple.
ASP.Net
private void BindGrid()
{
gridview1.DataSource = Get();
gridView1.DataBind();
}
Winforms
Same as above except we need not call DataBind().

C# how to prevent duplicated data in the database?

how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}

Categories