Edit a listview line on another page with textboxes - c#

I have to create a page an aspx page that allows me to modify the data of the listview row that are associated to a db, but I can't get the values.
I tried to do a query string
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
and to take the value on the page where I need it
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
but I don't know how to display the line I want to edit in the textboxes.
this is the button that redirects to the edit page
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
this is the edit page
public partial class Edit : System.Web.UI.Page
{
string constr =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
protected void CustomerUpdate(object sender, EventArgs e)
{
CustomerUpdate();
}
private int Id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["ID"]) ? int.Parse(Request.QueryString["ID"]) : 0;
}
}
private void CustomerUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persona SET Nome=#Nome, Cognome=#Cognome,Email=#Email,CodiceFiscale=#CodiceFiscale WHERE ID=#ID", con))
{
cmd.Parameters.AddWithValue("Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("Email", TextBox20.Text);
cmd.Parameters.AddWithValue("CodiceFiscale",TextBox22.Text);
cmd.Parameters.AddWithValue("ID", "");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri, false);
Response.Redirect("Dash.aspx");
}
}
}
}

I think that you shuld make public the methods which sends the information like the query but i'm not sure that will work.

I solved that
if (queryy == "1")
{
B2.Visible = false;
var connectionString =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM
Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID",
Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
TextBox1.Text = rdr["Nome"].ToString();
TextBox15.Text = rdr["Cognome"].ToString();
TextBox20.Text = rdr["Email"].ToString();
TextBox22.Text = rdr["CodiceFiscale"].ToString();
}
}
}
}

Related

How can I add search button code where I just want to find record and want to display it in listBoxes

I am new to C# and I am making a simple database project in which I want to add a functionality in which if user enter the identity number and click the button all the records will be displayed in the list boxes... Please help me to complete it... the code I want to add is in the last section of the code in button2_click.
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 System.Data.SqlClient;
namespace main_form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=windowDb;Integrated Security=True;Pooling=False");
SqlCommand command = new SqlCommand();
//SqlDataReader dataSearch;
private void Form1_Load(object sender, EventArgs e) {}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) {}
private void btn_save_Click(object sender, EventArgs e)
{
if(id_Txt.Text!=""& f_txt.Text!=""& Lname_txt.Text!=""& m_txt.Text!=""& dateTimePicker1.Text!=""){
command.Connection = con;
con.Open();
command.CommandText = "insert into people(id,fname,lname,mobile,TDATE) values('"+id_Txt.Text+"','"+f_txt.Text+"','"+Lname_txt.Text+"','"+m_txt.Text+"','"+dateTimePicker1.Text/*Value.ToString()*/+"')";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void search() {
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
listBox5.Items.Clear();
con.Open();
command.CommandText = "select * from people";
command.Connection = con;
SqlDataReader dataSearch = command.ExecuteReader();
if(dataSearch.HasRows){
while (dataSearch.Read())
{
listBox1.Items.Add(dataSearch["id"].ToString());
listBox2.Items.Add(dataSearch["fname"].ToString());
listBox3.Items.Add(dataSearch["lname"].ToString());
listBox4.Items.Add(dataSearch["mobile"].ToString());
listBox5.Items.Add(dataSearch["TDATE"].ToString());
}
}
con.Close();
}
private void btn_view_Click(object sender, EventArgs e)
{
search();
}
private void bn_update_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "" & f_txt.Text != "" & Lname_txt.Text != "" & m_txt.Text != "" & dateTimePicker1.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "update people set fname='" + f_txt.Text + "',lname='" + Lname_txt.Text + "',mobile='" + m_txt.Text + "',TDATE='" + dateTimePicker1.Text + "' where id='" +id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data updated Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox list = sender as ListBox;
if(list.SelectedIndex!=-1)
{
listBox1.SelectedIndex = list.SelectedIndex;
listBox2.SelectedIndex = list.SelectedIndex;
listBox3.SelectedIndex = list.SelectedIndex;
listBox4.SelectedIndex = list.SelectedIndex;
listBox5.SelectedIndex = list.SelectedIndex;
// retrive to TextBox of AllowDrop events;
/* id_Txt.Text = listBox1.SelectedIndex.ToString();
f_txt.Text = listBox2.SelectedIndex.ToString();
Lname_txt.Text = listBox3.SelectedIndex.ToString();
m_txt.Text = listBox4.SelectedIndex.ToString();
dateTimePicker1.Value = DateTime.Now;*/
id_Txt.Text = listBox1.SelectedItem.ToString();
f_txt.Text = listBox2.SelectedItem.ToString();
Lname_txt.Text = listBox3.SelectedItem.ToString();
m_txt.Text = listBox4.SelectedItem.ToString();
dateTimePicker1.Value = DateTime.Now;
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "delete from people where id='" + id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data deleted Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void label1_Click(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {}
private void button2_Click(object sender, EventArgs e)
{
if (text_search.Text == "")
{
MessageBox.Show("Enter the Rollno.");
}
else {
}
}
}
}

Automatic insertion of ID in execution

I have created inserting Employee details in Visual studio 2010.When I click on Add,it displays as added and the id automatically increments in backend.But instead of added,if I had to display as ("You EMP ID is somenumber(eg.10) )in front end while execution,what should I do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HRMSController;
using HRMSBusinessEntities;
using System.Data;
namespace HumanResourceManagementSystems
{
public partial class HRMSEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = (string)(Session["LoginUser"]);
if (Session["LoginUser"] != null)
{
lblDisplay.Text = "Welcome..." + username;
}
Calendar1.Visible = false;
Label1.Visible = false;
txtcurrdate.Text = System.DateTime.Now.ToLongDateString();
}
protected void Btnmodified_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Added" ;
Clear();
}
public void Clear()
{
txtname.Text = "";
txtcurrdate.Text = "";
txtmodifieddate.Text = "";
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtmodifieddate.Text = Calendar1.SelectedDate.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
Clear();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
}
}
After adding the record you can pull up the max id record and show the record in the UI
Query might look like
Select * from Employee ORDER BY EmpId DESC LIMIT 1;
As suggested for performance issue we can do
Select max(EmpId) from Employee;
EDIT
add.Add(record);
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
Label1.Visible = true;
Label1.Text = Your Empl ID is " + LastID[0].ToString() ;
Clear();
con.Close();
Another way could be
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Your Empl ID is " + FetchLastID();
Clear();
}
public string FetchLastID()
{
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
return LastID[0].ToString() ;
}

textBoxName.Text isn't getting the text entered by user, only the text that was set there on load

I have this textbox:
<asp:TextBox ID="txtDescription" runat="server" Height="90%" TextMode="MultiLine" Width="90%"></asp:TextBox>
and I set its' text value:
description = reader["Description"].ToString();
txtDescription.Text = description;
This is for editing the "description" so I have the existing description in the box and then want to get the text that is in the box at the end as it has been altered.
However I do:
string newDecription = txtDescription.Text;
and the value is that which it was initially set as. The above code to get the text value is ran on a submit button, so isn't somehow running and getting the value before it has been edited.
CONTEXT
protected void Page_Load(object sender, EventArgs e)
{
getValues();
}
string ID = 1;
protected void getValues()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand("SELECT Name,Stock,Price250g,Price1kg,Description,StockOrdered FROM Stock WHERE id = #ID", conn))
{
comm.Parameters.AddWithValue("#ID", ID);
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
price250g = reader["Price250g"].ToString();
price1kg = reader["Price1kg"].ToString();
name = reader["Name"].ToString();
description = reader["Description"].ToString();
stock = reader["Stock"].ToString();
stockOrdered = Convert.ToBoolean(reader["StockOrdered"].ToString());
lblName.Text = name;
lbl250g.Text += price250g.Remove(price250g.Length - 2);
lbl1kg.Text += price1kg.Remove(price1kg.Length - 2);
lblStock.Text = stock + "g";
cbStockOrdered.Checked = stockOrdered;
txtDescription.Text = description;
}
}
}
}
private void addAddressToOrder()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Stock SET Name=#name, Stock=#stock, Price250g=#price250, Price1kg=#price1kg, Description=#description, StockOrdered=#ordered WHERE Id=#ID", conn))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#description", txtDescription.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#price250", txtPrice250g.Text);
cmd.Parameters.AddWithValue("#price1kg", txtPrice1kg.Text);
stock = ddAddStock.SelectedValue + stock;
cmd.Parameters.AddWithValue("#stock", stock);
cmd.Parameters.AddWithValue("#ordered", cbStockOrdered.Checked);
conn.Open();
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
addAddressToOrder();
Response.Redirect("~/Admin/AdminHome.aspx");
}
This commonly happens when you do this:
protected void Page_Load(object sender, EventArgs e)
{
// other code
txtDescription.Text = description;
}
The reason is because of the page lifecycle events. Page_Load executes every time the page is loaded. This includes post-backs. (After all, you need to load the page in order to interact with it.) And it runs before any button handlers or other similar control events. So if this code, which writes a value to the text box, is executing before you read a value from the text box then it's going to overwrite that value.
Any code in Page_Load (or similar page initialization events) which shouldn't run on post-backs needs to be wrapped in a conditional:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// other code
txtDescription.Text = description;
}
}

Upload documents to Access DB using c#

I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}

Store the ListBox2 items in SQL table

In my Web Page, I have 2 List Boxes namely ListBox1,ListBox2.The user select the list of items from ListBox1 and move it to ListBox2.I done up to this, but after i click the 'SAVE' button, it is not save the ListBox2 selected item in the SQL table and It is not throw any error!! how to store it ?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblPage1ID.Text=Server.UrlDecode(Request.QueryString["Parameter"].ToString());
ListBoxWorksPackages();
}
}
protected void ListBoxWorksPackages()
{
ListBox1.Items.Add("General Contractor");
ListBox1.Items.Add("Architecture");
ListBox1.Items.Add("Civil");
ListBox1.Items.Add("Mechanical");
ListBox1.Items.Add("Electrical");
}
protected void btnMoveRight1_Click(object sender, EventArgs e)
{
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListItem li = ListBox1.Items[i];
ListBox1.Items.Remove(li);
}
}
}
protected void btnMoveLeft1_Click(object sender, EventArgs e)
{
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListItem li = ListBox2.Items[i];
ListBox2.Items.Remove(li);
}
}
}
protected void BtnSave1_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
string Packagevalues = string.Empty;
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected == true)
{
Packagevalues += "," + item.Text;
}
}
string query = "INSERT INTO Contractor_Info2 (Vendor_ID,WorksPackage) VALUES"
+ "(#Vendor_ID,#WorksPackage )";
try
{
SqlCommand cmd = new SqlCommand(query, SqlCon);
cmd.CommandType = CommandType.Text;
SqlCon.Open();
cmd.Parameters.AddWithValue("#Vendor_ID", lblPage1ID.Text);
cmd.Parameters.AddWithValue("#WorksPackage", Packagevalues);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
SqlCon.Close();
}
}
you need to call cmd.ExecuteNonQuery() after you've added the parameters to your sql procedure. this is what will actually run your sql statement.
try
{
SqlCommand cmd = new SqlCommand(query, SqlCon);
cmd.CommandType = CommandType.Text;
SqlCon.Open();
cmd.Parameters.AddWithValue("#Vendor_ID", lblPage1ID.Text);
cmd.Parameters.AddWithValue("#WorksPackage", Packagevalues);
// add this
cmd.ExecuteNonQuery();
}

Categories

Resources