I have a problem when click on submit button. the data still insert into database even though there is an invalid data.
public partial class surveyCreate : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
private string lblTextMessage;
protected void Page_Load(object sender, EventArgs e)
{
btnSubmitSurvey.Attributes.Add("onclick", "return PostPage();");
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
if (!IsPostBack)
{
int a_unit = 0;
string username = (string)Session["Username"];
string query5 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd5 = new SqlCommand(query5, con);
SqlDataReader dr5 = cmd5.ExecuteReader();
if (dr5.Read())
{
a_unit = Convert.ToInt32(dr5["a_unit"]);
}
dr5.Close();
con.Close();
string queryA = "";
string queryB = "";
string queryC = "";
queryA = "SELECT * FROM tblUnit WHERE u_master = " + a_unit;
queryB = "SELECT * FROM tblProject ";
queryC = "SELECT * FROM tblSurveyTemplate where st_template = " + a_unit;
BindDropDownList(ddlunit, queryA, "u_name", "u_id", "SELECT UNIT");
//BindDropDownList(project, queryB, "pro_name", "pro_id", "SELECT PROJECT");
BindDropDownList(ddlTemplate, queryC, "st_name", "st_id", "SELECT TEMPLATE");
ddlproject.Enabled = false;
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
// string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void unit_SelectedIndexChanged(Object sender, EventArgs e)
{
ddlproject.Enabled = true;
int u_id = int.Parse(ddlunit.SelectedItem.Value);
string query = "Select pro_id, pro_name from tblProject WHERE u_id=" + u_id;
BindDropDownList(ddlproject, query, "pro_name", "pro_id", "SELECT PROJECT");
}
protected void ddlTemplate_SelectedIndexChanged(Object sender, EventArgs e)
{
int st_id = int.Parse(ddlTemplate.SelectedItem.Value);
SqlDataSourceQuestions.SelectCommand = "SELECT sq_id, sq_question FROM tblSurveyQuestions WHERE st_id=" + st_id;
string query = "SELECT * FROM tblSurveyTemplate WHERE st_id=" + st_id;
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
LabelComment.Text = dr["st_comment"].ToString();
LabelIntro.Text = dr["st_intro"].ToString();
}
dr.Close();
con.Close();
if (st_id != 0)
PanelA.Visible = true;
else
PanelA.Visible = false;
}
/**
protected void project_SelectedIndexChanged(Object sender, EventArgs e)
{
project.Enabled = true;
project.Items.Clear();
project.Items.Insert(0, new ListItem("SELECT PROJECT", "0"));
int unitId = int.Parse(unit.SelectedItem.Value);
if (unitId > 0)
{
string query = string.Format("Select pro_id, pro_name from tblProject where pro_id = {0} ", unitId);
BindDropDownList(project, query, "pro_name", "pro_id", "SELECT PROJECT");
project.Enabled = true;
}
}
static int i = 0;
protected void btn_addp_Click(object sender, EventArgs e)
{
int j = 0;
i++;
for (j = 0; j < i; j++)
{
TextBox tb = new TextBox();
tb.Width = 350;
tb.ID = "MP" + j.ToString();
ph.Controls.Add(tb);
}
}
*/
protected void btn_addp_Click(object sender, EventArgs e)
{
int index = pnlTB.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox tb = new TextBox();
tb.ID = id;
tb.Width = 350;
pnlTB.Controls.Add(tb);
Literal lt = new Literal();
lt.Text = "<div style=height:3px ></div>";
pnlTB.Controls.Add(lt);
pnlTB.Controls.Add(new LiteralControl("<div style=height:3px ></div>"));
}
protected void GetTextBoxValues(object sender, EventArgs e)
{
}
//duplicate email
protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
{
//TextBox[] participant = { participant1, participant2, participant3 };
//if (participant1.Text == participant2.Text || participant2.Text == participant3.Text || participant1.Text == participant3.Text)
//{
// cvSubmit.ErrorMessage = "* Duplicate email! Please enter different email. ";
// cvSubmit.Focus();
// e.IsValid = false;
//}
}
here is the code for submit
protected void btnSubmitSurvey_Click(object sender, EventArgs e)
{
string a_id = "";
string username = (string)Session["Username"];
string query4 = "SELECT * FROM tblAdmin WHERE a_uname='" + username + "'";
con.Open();
SqlCommand cmd4 = new SqlCommand(query4, con);
SqlDataReader dr4 = cmd4.ExecuteReader();
if (dr4.Read())
{
a_id = dr4["a_id"].ToString();
}
dr4.Close();
con.Close();
if (Page.IsValid)
{
con.Open();
string query = "CreateSurvey";
string query1 = "ListParticipant";
int surveyID;
DateTime date_now = DateTime.Now;
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sd_id", SqlDbType.Int, 0, "sd_id");
cmd.Parameters["#sd_id"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#sd_title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.Add("#sd_unit", SqlDbType.NVarChar).Value = ddlunit.SelectedValue;
cmd.Parameters.Add("#sd_project", SqlDbType.NVarChar).Value = ddlproject.SelectedValue;
cmd.Parameters.Add("#sd_year", SqlDbType.NVarChar).Value = txtYear.Text;
cmd.Parameters.Add("#st_id", SqlDbType.NVarChar).Value = ddlTemplate.SelectedValue;
cmd.Parameters.Add("#sd_datecreated", SqlDbType.DateTime).Value = date_now;
cmd.Parameters.Add("#sd_createdBy", SqlDbType.NVarChar).Value = a_id;
cmd.ExecuteNonQuery();
surveyID = (int)cmd.Parameters["#sd_id"].Value;
//validate email
bool email = Regex.IsMatch(participant.Text.Trim(), "\\w+([-+.']\\w+)*#\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
if (!email)
{
lbl2.Text = "Invalid email address";
return;
}
else
{
lbl2.Text = "";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = participant.Text;
cmd1.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd1.ExecuteNonQuery();
}
foreach (TextBox textBox in pnlTB.Controls.OfType<TextBox>())
{
if (textBox.Text != "")
{
SqlCommand cmd2 = new SqlCommand(query1, con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#sp_email", SqlDbType.NVarChar).Value = textBox.Text;
cmd2.Parameters.Add("#sd_id", SqlDbType.Int).Value = surveyID;
cmd2.ExecuteNonQuery();
}
}
string message = "Your survey details has been saved.";
string url = "surveyConfirm.aspx?surveyId=" + surveyID;
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += url;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
con.Close();
}
else
{
lbl2.Text = "Fill up the information required";
}
}
}
someone please help me to solve this problem. thank you
Related
I have connection with local database. I wanted full name from (in this case) combobox4 to textbox textbox. It displays this value but without separation with space. For example from combobox4 "S BOX" in textbox is only "S". I tried with textBox4.Text = string.Join(" ", parts[1]); but i couldn't work. I share my code:
Insertstatus.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace KontrolaBazaDanych
{
public partial class InsertStatus : Form
{
string Zlecenie_wykonane;
string Zlecenie_rozpoczete;
MySqlConnection connection;
MySqlCommand command;
MySqlDataReader dr;
Form1 frm1 = (Form1)Application.OpenForms["Form1"];
public InsertStatus()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
string InsertQuery = "INSERT INTO projekt1.status_zl(ID_ZLECENIA, ID_PRACOWNIKA, ID_MODULU, ID_PROJEKTU, ILOSC_PRODUKTOW, DATA_ROZPOCZECIA, DATA_ZAKONCZENIA, ZLECENIE_WYKONANE, ZLECENIE_ROZPOCZETE) VALUES('" + textBox7.Text + "','" + textBox9.Text + "','" + textBox8.Text + "','"+ textBox10.Text +"','" + numericUpDown4.Value.ToString() + "','" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss") + "','" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Zlecenie_wykonane + "','" + Zlecenie_rozpoczete + "')";
connection.Open();
MySqlCommand command = new MySqlCommand(InsertQuery, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Dane są dodane.");
}
else
{
MessageBox.Show("Błąd.");
}
frm1.loaddata4();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
numericUpDown4.Value = 0;
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now;
checkBox1.Checked = false;
checkBox2.Checked = false;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Zlecenie_wykonane = "1";
Zlecenie_rozpoczete = "0";
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
Zlecenie_wykonane = "0";
Zlecenie_rozpoczete = "1";
}
private void InsertStatus_Load(object sender, EventArgs e)
{
connection = new MySqlConnection();
connection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
connection.Open();
string selectQuery2 = "SELECT * FROM projekt1.pracownicy";
MySqlCommand command2 = new MySqlCommand(selectQuery2, connection);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
comboBox1.Items.Add(reader2.GetString("ID_PRACOWNIKA") + " " + reader2.GetString("IMIE") + " " + reader2.GetString("NAZWISKO"));
}
connection.Close();
connection.Open();
string selectQuery3 = "SELECT * FROM projekt1.moduly";
MySqlCommand command3 = new MySqlCommand(selectQuery3, connection);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
comboBox2.Items.Add(reader3.GetString("NAZWA"));
}
connection.Close();
connection.Open();
string selectQuery4 = "SELECT * FROM projekt1.zlecenia";
MySqlCommand command4 = new MySqlCommand(selectQuery4, connection);
MySqlDataReader reader4 = command4.ExecuteReader();
while (reader4.Read())
{
comboBox3.Items.Add(reader4.GetString("NUMER_ZLECENIA"));
}
connection.Close();
connection.Open();
string selectQuery5 = "SELECT * FROM projekt1.projekty";
MySqlCommand command5 = new MySqlCommand(selectQuery5, connection);
MySqlDataReader reader5 = command5.ExecuteReader();
while (reader5.Read())
{
comboBox4.Items.Add(reader5.GetString("ID") + " " + reader5.GetString("NAZWA_PROJEKTU"));
}
connection.Close();
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
textBox7.Enabled = false;
textBox8.Enabled = false;
textBox9.Enabled = false;
textBox10.Enabled = false;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
command = new MySqlCommand("SELECT * FROM projekt1.moduly WHERE NAZWA='"+ comboBox2.Text +"'", connection);
connection.Open();
command.ExecuteNonQuery();
MySqlDataReader dr;
dr = command.ExecuteReader();
while (dr.Read())
{
string nazwa = (string)dr["NAZWA"].ToString();
textBox3.Text = nazwa;
string id_modulu = (string)dr["ID_MODULU"].ToString();
textBox8.Text = id_modulu;
}
connection.Close();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
command = new MySqlCommand("SELECT * FROM projekt1.zlecenia WHERE NUMER_ZLECENIA='" + comboBox3.Text+"'", connection);
connection.Open();
command.ExecuteNonQuery();
dr = command.ExecuteReader();
while (dr.Read())
{
string opis = (string)dr["OPIS_ZLECENIA"].ToString();
textBox5.Text = opis;
string numer = (string)dr["NUMER_ZLECENIA"].ToString();
textBox6.Text = numer;
string status_zl = (string)dr["ID_ZLECENIA"].ToString();
textBox7.Text = status_zl;
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1)
{
string[] parts = comboBox1.Items[comboBox1.SelectedIndex].ToString().Split(' ');
textBox9.Text = parts[0];
textBox1.Text = parts[1];
textBox2.Text = parts[2];
}
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox4.SelectedIndex != -1)
{
string[] parts = comboBox4.Items[comboBox4.SelectedIndex].ToString().Split(' ');
textBox10.Text = parts[0];
textBox4.Text = string.Join(" ", parts[1]);
}
}
}
}
I can't find any solution which may be effective. It's about string.Join construction or should create public class? Has someone idea how to solve it or explain by example code? Greetings.
Okey i've got that solution which i can do that and it's for now solved:
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox4.SelectedIndex != -1)
{
string[] parts = comboBox4.Items[comboBox4.SelectedIndex].ToString().Split(' ');
textBox10.Text = parts[0];
textBox4.Text = comboBox4.Text.Remove(0,2).Trim();
}
I am 100% sure my listview has data. My program will get the ID from the column 0 of my listview, connects to the database, and using the ID as my reference will get the data from my database and display it to my textboxes/comboboxes. SO when I click an item from my listview, an exception appears and all of my textboxes as well as my comboboxes are empty. I am new to c# and programming, any help will be much appreciated.
using System;
using System.Data.OleDb;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private string button = null;
private string carID;
public Form1()
{
InitializeComponent();
textDateReg.Text = DateTime.Now.ToString();
lvRefresh();
}
private void lvRefresh()
{
listView1.Items.Clear();
listView1.View = View.Details;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand("Select ID, PlateNo from Cars", con);
OleDbDataReader cmdrdr = cmd.ExecuteReader();
if (cmdrdr.HasRows)
{
while (cmdrdr.Read())
{
ListViewItem list = new ListViewItem(cmdrdr["ID"].ToString());
list.SubItems.Add(cmdrdr["PlateNo"].ToString());
listView1.Items.Add(list);
}
}
con.Close();
cmdrdr.Close();
cmd.Dispose();
}
private void buttonNew_Click(object sender, EventArgs e)
{
button = "new";
buttonSub.Enabled = true;
panel1.Enabled = true;
}
private void textBox7_MouseClick(object sender, MouseEventArgs e)
{
textBox7.Text = null;
}
private void buttonSub_Click(object sender, EventArgs e)
{
switch (button)
{
case "new":
DialogResult dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Insert into Drivers (FirstName,MiddleName,LastName,Address,Age,PhoneNo,Gender,RegDate) Values (#FirstName,#MidName,#LastName,#Address,#Age,#Phone,#Gender,#RegDate)", con);
con.Open();
cmd.Parameters.Add(new OleDbParameter("#FirstName", Fname));
cmd.Parameters.Add(new OleDbParameter("#MidName", Mname));
cmd.Parameters.Add(new OleDbParameter("#LastName", Lname));
cmd.Parameters.Add(new OleDbParameter("#Address", Adrs));
cmd.Parameters.Add(new OleDbParameter("#Age", Age));
cmd.Parameters.Add(new OleDbParameter("#Phone", Phone));
cmd.Parameters.Add(new OleDbParameter("#Gender", Gender));
cmd.Parameters.Add(new OleDbParameter("#RegDate", RegDate));
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd = new OleDbCommand("Insert into Cars(Color, Brand, Model, Type, PlateNo) Values(#Color, #Brand, #Model, #Type, #PlateNo)", con);
cmd.Parameters.Add(new OleDbParameter("#Color", Color));
cmd.Parameters.Add(new OleDbParameter("#Brand", Brand));
cmd.Parameters.Add(new OleDbParameter("#Model", Model));
cmd.Parameters.Add(new OleDbParameter("#Type", Type));
cmd.Parameters.Add(new OleDbParameter("#PlateNo", PlateNo));
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
MessageBox.Show("Record Submitted", "Nice!");
lvRefresh(); //refresh listview
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
break;
case "del":
dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
}
catch
{
}
}
break;
case "edit":
break;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Enabled = true;//panel that contains my textboxes/comboboxes
buttonDel.Enabled = true;
try
{
ListViewItem item = listView1.SelectedItems[0];
carID = item.Text;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from Drivers where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.HasRows)
{
textFN.Text = rdr["FirstName"].ToString();
textMN.Text = rdr["MiddleName"].ToString();
textLN.Text = rdr["LastName"].ToString();
textADRS.Text = rdr["Address"].ToString();
textPHONE.Text = rdr["PhoneNo"].ToString();
textDateReg.Text = rdr["RegDate"].ToString();
textAGE.Text = rdr["Age"].ToString();
comboGender.Text = rdr["Gender"].ToString();
if (!rdr.HasRows)
{
rdr.Close();
cmd.Dispose();
OleDbCommand cmdc = new OleDbCommand("Select * from Cars where ID = #ID", con);
cmdc.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdrc = cmdc.ExecuteReader();
while (rdrc.HasRows)
{
textColor.Text = rdr["Color"].ToString();
comboType.Text = rdr["Type"].ToString();
textBrand.Text = rdr["Brand"].ToString();
textModel.Text = rdr["Model"].ToString();
textPlateNo.Text = rdr["PlateNo"].ToString();
}
rdrc.Close();
cmdc.Dispose();
con.Close();
}
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
}
}
I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}
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
I wanted to know if there was a way to select a row and delete on right click from grid view.
I have the delete statement but I just dont have how to select on right click.
I've seen a couple suggestions that say to use mousebuttons.right but that doesnt work for me and errors with the (mousebuttons does not exist in current context)
here is my current fill statement
protected void getGLDepts()
{
mpSearch.Focus();
string[] mpvalue = mpSearch.Text.Split('(',')');
string coa = "";
string map = "";
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_GET_GL_BY_DEPT";
cmd.Parameters.Add("#DEPTCODE", SqlDbType.Int).Value = mpvalue[1].ToString();
foreach (ListItem item in mpcbl.Items)
{
if (item.Selected)
{
coa += "','" + item.Value;
}
}
if (coa != "") coa = coa.Substring(2, coa.Length - 2) + "'";
else coa = "''";
cmd.Parameters.Add("#COA", SqlDbType.VarChar).Value = coa;
foreach (ListItem item in exceptdefault.Items)
{
if (item.Selected)
{
map += "','" + item.Value;
}
}
if (map != "") map = map.Substring(2, map.Length - 2) + "'";
else coa = "''";
cmd.Parameters.Add("#MAP", SqlDbType.VarChar).Value = map;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
gvMapping.DataSource = ds;
gvMapping.DataBind();
lblGLDeptData.ForeColor = System.Drawing.Color.Black;
lblGLDeptData.Text = " " + ds.Tables[0].Rows.Count + " Cost Center/Funds are Mapped to this Department.";
}
else
{
gvMapping.DataSource = ds;
gvMapping.DataBind();
lblGLDeptData.ForeColor = System.Drawing.Color.Black;
lblGLDeptData.Text = " No Currently Mapped Cost Centers.";
}
}
catch (Exception ex)
{
lblGLDeptData.ForeColor = System.Drawing.Color.Red;
lblGLDeptData.Text = ex.Message;
}
finally
{
myconn.Close();
myconn.Dispose();
}
my select row statement
protected void gvSelect(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Cells[0].Style["display"] = "none";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.gvMapping, "Select$" + e.Row.RowIndex);
}
}
and my delete statement
protected void delSysGLDepts(object sender, EventArgs e)
{
if (cbsys.Checked && !cbgl.Checked)
{
GridViewRow row = gvMapping.SelectedRow;
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = myconn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_DELETE_SYS_ROW";
cmd.Parameters.Add("#SYSID", SqlDbType.Int).Value = row.Cells[1].Text;
myconn.Open();
object count = cmd.ExecuteNonQuery();
myconn.Close();
myconn.Dispose();
getSysDepts();
Works well for me:
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onContextMenu ", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()) + "; return false;");
}
}
protected override void Render(HtmlTextWriter writer)
{
for (int index = 0; index < GridView1.Rows.Count; index++)
{
ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" + index.ToString());
}
base.Render(writer);
}