Insert data into Access database upon checkbox-click event of ASP.net - asp.net

I'm trying to make asp.net page
Criteria
I have product list. (using listview)
ProductID Proudct name Price ADD TO CART(checkbox)
Now I am using access 2007 for database. C# for code behind file. I want add product in to database which is on the event of checkbox. So if user check 10 item check box Out of 20 . I want write insert query on event of checkbox
Is it possible to do it? If it possible please provide me knowledge/ code how can I do it?
Please keep in mid that I am new and learning stage so make it easy or put gudieline in comments.

It sounds like you want to use the OnCheckedChanged event.
<asp:CheckBox ID="CheckBox1" runat="server" Text="Hello World!" OnCheckedChanged="CheckBox1_CheckedChanged" />
And in your code behind:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
//CREATE CONNETION HERE
OleDbConnection conn = new OleDbConnection ("<YOUR CONNECTION STRING HERE>");
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
//CREATE YOUR OWN INSERT/UPDATE COMMAND HERE
command.CommandText= "<YOUR COMMAND TEXT HERE>";
command.Parameters.Add ("#Argument1", OleDbType.String).Value = CheckBox1.Text;
command.ExecuteNonQuery();
conn.Close();
}

Related

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

Delete row in GridView using Two DataKeys in condition

I want to delete a row in GridView and database as well.. I already have a stored procedure for the delete, the method is also created, but my problem is how can i use Two datakeys for my where clause. I've search and saw a lot of answers but they are using CommandArgument and that is applicable only in 1 datakeys.
I want something like this.
DELETE FROM TableName WHERE ID = Variable1 AND Name = Variable2
What i want is how can i retrieve the values of 2 datakeys in GridView if i set DataKeys like: DataKeys="ID, Name"
Any help would be appreciated.
Thanks
(if I correctly understood you)
stored procedure
Create Procedure [dbo].[Procedure_Name](
#Variable1 type(),
#Variable2 type() --you can add as many variables as you want, but then you have to add them in c# code as a parameters.
) as
delete from Table_Name
where Table_Name.Variable1 = #Variable1 AND Table_Name.Variable2 = #Variable2
with button in aspx code
<asp:Button ID="btnDeleteSomething" runat="server" Text="Delete Something" OnClick="btnDeleteSomething_Click"/>
then in c# codebehind
protected void btnDeleteSomething_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_NAME"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Procedure_Name", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
cmd.Parameters.Add("#Variable1", SqlDbType.VarChar, 70(its example with varchar)).Value = Variable1.Text(every Textbox, or label, or dropdownlist)
cmd.Parameters.Add("#Variable2", SqlDbType.Int).Value = Session["UserID]" - For example if u want do delete with parameter focused on user;
try
{
int rows = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
And it works fine without Datakeys at all. If u want to do it "with" then u have to add ControlParameter in your SqlDataSource. Hope it's going to help you.
Finally i found the solution on this link:
http://www.aspsnippets.com/Articles/Using-Multiple-DataKeyNames-DataKeys-in-ASPNet-GridView-with-examples.aspx
here is what exactly im looking for..
Dim rowIndex As Integer = TryCast(TryCast(sender, ImageButton).NamingContainer GridViewRow).RowIndex
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))`
Dim Name As String = GridView1.DataKeys(rowIndex).Values(1).ToString()`
Thanks

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

how to set column as readonly in gridview

I am using a gridview Edit to edit the values i have in my gridview, when i press edit, all columns can be edited, i would like that one of the columns is not allowed to be edited.
Is there any way i can do this?
This is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
onrowdeleting="GridView1_RowDeleting" AutoGenerateEditButton="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" >
</asp:GridView>
This is my aspx.cs code:
public void loadCustomer()
{
SqlConnection objConnection = new SqlConnection("Data Source=localhost;Initial Catalog=SampleApplication;Integrated Security=True");
objConnection.Open();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandText = "Select * from Customer";
objCommand.Connection = objConnection;
objCommand.ExecuteNonQuery();
DataSet objds = new DataSet();
SqlDataAdapter objadap = new SqlDataAdapter(objCommand);
objadap.Fill(objds);
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
objConnection.Close();
}
RowDataBound event of gridView1
((BoundField)gridView1.Columns[columnIndex]).ReadOnly = true;
I know this is really old but I need to put the answer here for others who shared my issue. Regardless, I've been struggling with this non-stop for a couple of days now. Everyone seems to be posting code for VB, when your problem is clearly posted in C#.
What you're looking for is:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columntobedisabled].Enabled = false;
}
where 'columntobedisabled' is index number of the column to be disabled...eg. 1
In case of C# Website or WebForm enter the following code in Page_Load() in code behind file
protected void Page_Load(object sender, EventArgs e)
{
// Your code
((BoundField)GridView1.Columns[columnIndex]).ReadOnly = true;
}
Doing this will also help in overcoming the error
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index'
You need to give rights "ReadOnly= true" to that column which you not like to be edit.
e.g .
GridView1.columns[1].ReadOnly= true;
You can use this line in RowDataBound event of GridView.

i have repeater with check boxes i wants to delete records when one or more check boxes are checked on button click event

i tried but its not working
codes are as follows
protected void Button_Click(object sender, CommandEventArgs e)
{
if (e.CommandName.Equals("Delete"))
{
foreach (RepeaterItem item in Repeater2.Items)
{
CheckBox chk = (CheckBox)item.FindControl("MyCheckBoxID");
if (chk.Checked)
{
SqlConnection cn1 = new SqlConnection("Data Source=192.168.1.64;Initial Catalog=arvind;User ID=sa;password=platinum50");
cn1.Open();
SqlCommand cmd = new SqlCommand("delete * from Employee_Login " ,cn1 );
}
}
}
}
the error is microsoft run time error-form name="Form1" method="post" action="Default.aspx" id="Form1" onsubmit="Check(this)" at this line and saying object is expected
You need to tell your SQL command the ID of the item you want to delete (you can store this in the CommandArgument property) otherwise it won't know which row to delete from the Employee_Login table.
Also, you also need to Execute your command - at the moment all you are doing is defining it.
And after you have executed your command, you need to rebind the repeater.
HTH.
EDIT:
PS. Take a look at this if you're still having problems: http://bit.ly/fnLFRx

Resources