Store the ListBox2 items in SQL table - c#

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();
}

Related

Edit a listview line on another page with textboxes

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();
}
}
}
}

CheckBox to select or deselect all the items of a column SQL

I have a SQL column of type bit (boolean), I can check or uncheck some items of my choice from a data grid, where those checkboxes are shown. Now I want to have a single checkbox to select or deselect all the checkboxes into the data grid. I've arrived at this code:
private void Chk_All_Checked(object sender, RoutedEventArgs e)
{
sqliteCon.Open();
if (sqliteCon.State == System.Data.ConnectionState.Open)
{
CORRENTE
string q = #"UPDATE tabL
SET selection = (CASE
WHEN (SELECT selection FROM tabL ) = 0
THEN 1
ELSE 0
END)
WHERE ?????????????????????";
SqlCommand cmd = new SqlCommand(q, sqliteCon);
cmd.ExecuteNonQuery();
MessageBox.Show("All Items Checked");
}
sqliteCon.Close();
}
"WHERE idL=#CURRENT" is wrong
Here is another try but isn't working as well:
private void Chk_All_Checked(object sender, RoutedEventArgs e)
{
sqliteCon.Open();
if (sqliteCon.State == System.Data.ConnectionState.Open)
{
string q = #"UPDATE tabL
SET selection = 1";
SqlCommand cmd = new SqlCommand(q, sqliteCon);
cmd.ExecuteNonQuery();
MessageBox.Show("All Items Checked");
string q2 = #"UPDATE tabL
SET selection = 0";
SqlCommand cmd2 = new SqlCommand(q2, sqliteCon);
cmd2.ExecuteNonQuery();
MessageBox.Show("All Items DeChecked");
}
sqliteCon.Close();
}
378 views 0 solutions but i've found one by my own
the chkbox object have got two event handlers one for checked and one for deceked.
private void Chk_All_Checked(object sender, RoutedEventArgs e)
{
sqliteCon.Open();
if (sqliteCon.State == System.Data.ConnectionState.Open)
{
if (chk_All.IsChecked == true) {
string q = #"UPDATE tabList
SET selection = 1";
SqlCommand cmd = new SqlCommand(q, sqliteCon);
cmd.ExecuteNonQuery();
MessageBox.Show("All Items Checked");
}
}
sqliteCon.Close();
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
sqliteCon.Open();
if (sqliteCon.State == System.Data.ConnectionState.Open)
{
if (chk_All.IsChecked == false)
{
string q2 = #"UPDATE tabList
SET selection = 0";
SqlCommand cmd2 = new SqlCommand(q2, sqliteCon);
cmd2.ExecuteNonQuery();
MessageBox.Show("All Items DeChecked");
}
}
sqliteCon.Close();
}
Use following code:
private void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Index == e.RowIndex)
{
row.Cells["checkBoxColumn"].Value =
!Convert.ToBoolean(row.Cells["checkBoxColumn"].EditedFormattedValue);
}
else
{
row.Cells["checkBoxColumn"].Value = false;
}
}
}
}

How to update items from datagridview in c#

I want to update invoice and invoice has multiple items i retrieve invoice items from Database to DataGridView now user can remove the items and can add the items and user will click on update button to update the invoice in database.
My Code:
try
{
using (SQLiteConnection con = new SQLiteConnection(AppSettings.ConnectionString()))
{
con.Open();
for (int j = 0; j < dgv.Rows.Count; j++)
{
using (SQLiteCommand sc = new SQLiteCommand("Update Orders Set [Order_No] = #Order_No,[Order_Type] = #Order_Type,[Order_Date] = #Order_Date,[Customer_Name] = #Customer_Name,[Contact] = #Contact,[Adress] = #Adress,[Delivery_Address] = #Delivery_Address,[Rider] = #Rider,[Items] = #Items,[Price] = #Price,[Qty] = #Qty,[Item_Total] = #Item_Total,[Item_Cat] = #Item_Cat,[SubTotal] = #SubTotal,[Discount] = #Discount,[Total_Amount] = #Total_Amount,[Paid_Amount] = #Paid_Amount,[Change_Due] = #Change_Due,[Delivery_Charges] = #Delivery_Charges Where Order_No = '" + Order_No.Text + "' ", con))
{
sc.Parameters.AddWithValue("#Order_No", Order_No.Text);
sc.Parameters.AddWithValue("#Order_Type", Order_Type.Text);
sc.Parameters.AddWithValue("#Order_Date", Order_Date.Text);
sc.Parameters.AddWithValue("#Customer_Name", Customer_Name.Text);
sc.Parameters.AddWithValue("#Contact", Contact.Text);
sc.Parameters.AddWithValue("#Adress", Address.Text);
sc.Parameters.AddWithValue("#Delivery_Address", Delivery_Address.Text);
sc.Parameters.AddWithValue("#Rider", "");
sc.Parameters.AddWithValue("#Items", dgv.Rows[j].Cells[1].Value);
sc.Parameters.AddWithValue("#Price", dgv.Rows[j].Cells[2].Value);
sc.Parameters.AddWithValue("#Qty", dgv.Rows[j].Cells[3].Value);
sc.Parameters.AddWithValue("#Item_Total", dgv.Rows[j].Cells[4].Value);
sc.Parameters.AddWithValue("#Item_Cat", dgv.Rows[j].Cells[5].Value);
sc.Parameters.AddWithValue("#SubTotal", SubTotal.Text);
sc.Parameters.AddWithValue("#Discount", Discount.Text);
sc.Parameters.AddWithValue("#Total_Amount", Total_Amount.Text);
sc.Parameters.AddWithValue("#Paid_Amount", Paid_Amount.Text);
sc.Parameters.AddWithValue("#Change_Due", Change_Due.Text);
sc.Parameters.AddWithValue("#Delivery_Charges", Del_Charges.Text);
sc.ExecuteNonQuery();
}
}
SuccessBox sb = new SuccessBox();
sb.lbl_Change.Text = Change_Due.Text;
sb.label1.Text = "Successfully Updated";
sb.ShowDialog();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if i add new item and click on update button so this query replaces my all old items with new one.
Suppose i add Samsung S8 so it willl replace my old items to Samsung S8.
And the result is:
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Is there any way to do this?
You have to Set The OrderID Parameter in order to Update the desired Item
This will do the Insert, Update, and Delete for you, all via a DataGrid object.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
public frmMain()
{
InitializeComponent();
DisplayData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(#name,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Record",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Record set Name=#name,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Record where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

DataList keep displaying previously loaded datalist

I have a catalog function whereby user can filter their selection by clicking radiobutton. For example, by selecting the Dining radiobutton, all packages related to dining would appear.
And i using DataList1.Items.Count method to count the number search result. I had implement this method in the page_load, however the value of the number of datalist keep displaying previously loaded datalist.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, CatName from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource1";
if (RadioButtonList1.SelectedIndex == 0)
{
Session["catID"] = 1;
}
else if (RadioButtonList1.SelectedIndex == 1)
{
Session["catID"] = 2;
}
else if (RadioButtonList1.SelectedIndex == 2)
{
Session["catID"] = 3;
}
else if (RadioButtonList1.SelectedIndex == 3)
{
Session["catID"] = 4;
}
else if (RadioButtonList1.SelectedIndex == 4)
{
Session["catID"] = 5;
}
else
{
Session["catID"] = 8;
}
}
I had tried to place the Item.Count in other places of this code, but same problem persist..
Try this,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
}

Categories

Resources