gridview With delete action .column needs to be updated - c#

I have a gridview with delete action.. particular row needs to be updated on it. I am getting errors when doing that.
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
How to write client side event for the gridview.
my gridview
please tel me how to rectify this errors..
requirement is to on clicking delete button, that row needs to be updated
to particular set values..

You are doing a wrong call to AddWithValue method. You are specifying a SqlDbType when AddWithValue is supposed to do it implicitly:
string yourId = "1";
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id", yourId);
Also, I donĀ“t see where you have the value Id that is supposed to be passed as parameter. I added yourId variable since there is not id value.
If you want to specify the type, dont use AddWithValue, use Add, instead:
string yourId = "1";
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Id", SqlDbType.NVarChar).Value = yourId;
Also, are you sure that ID column should be NVarChar??

private void Page_Load()
{
if (!IsPostBack)
{
//Bind Date
}
}
alterantively you can
EnableEventValidation="false"
but that is not recommended

Related

How to initialize login functionality in Site.Master form to pull Login ID from SQL after redirect?

How do I save results of a logged in user after successful redirect from the Login page or Sign up page? I have a button in the Site.Master parent form, which is loaded with every other web form. I want to get the ID of the logged in user from my SQL database and populate a textbox in a form for Reservation.
My project is in ASP.NET about making room reservations. I have a login in button in the Master Form, which consists of a navigation bar with 8 menu buttons each redirecting to a different Web Page. The data in the Login Form is checked with my SQL server, and upon successful login, the user is redirected to the reservation page. My idea was to declare 2 global variables like a bool, checking if user is logged in on every redirect and an empty string, which gets the value of User ID from SQL if bool LoggedIn is true. But I was unsuccessful in initializing the global variables and calling them in the child form (Booking form) and frankly, I'm not sure if I've taken the right approach to achieving this.
My code in Login_in.aspx.cs for login redirect is the following:
protected void Button1_Click(object sender, EventArgs e)
{
String source = #"Data Source=DESKTOP;Initial Catalog=projectX;Integrated Security=true;";
SqlConnection con = new SqlConnection(source);
{
try
{
string uid = TextBox1.Text;
string pass = TextBox2.Text;
con.Open();
string query = "select * from Users where Username='" + uid + "' and Password='" + pass + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
Response.Redirect("~/Booking.aspx");
}
else
{
Label10.Text = "Wrong pass or username!";
}
con.Close();
Label10.Visible = true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I'm not sure if I have to declare the global variables for bool LoggedIn and string UserID in the Login Form or the Master Form, but I want to change their values upon Response.Redirect("~/Booking.aspx"). If they are declared in the Site.Master.cs file, how can I change their values in the Login form and call them (and their values) in the Booking form. I've tried declaring them as
public static bool LoggedIn = false;
public static string userID;
but wasn't sure how to initialize the get & set properties between forms.
In my Booking form I have a textbox which I want to populate with the username of the loggedIn user by userID (from sql).
How do I set the properties in the form where the variables are declared and in the forms, where they are called?
ASP.NET Web Forms supports two ways to secure your web application:
The old one, Forms Authentication
The modern, ASP.NET Identity
They both provide you with the infrastructure to authenticate and authorize users as well as access to the logged in user. They both use a database as storage. Various techniques are used to identify an authenticated user between requests such as cookies.
It is highly recommended that you use either in your application. There are tons of documentation to read about.
On the other hand, implementing your own security system is going to be difficult, error-prone, time consuming, inefficient and ultimately insecure.

How to pass selected date from AJAX calendar Control into stored procedure

I have written an insert stored procedure in oracle 11g. I am able to pass all the values except date value which I am getting from an Ajax calendar control in asp.net page
I have textbox with this control, when user select the date from calendar control it will display in that textbox. How to pass the textbox value into the stored procedure?
Written in C# for asp.net application
Some of ways I tried
command.Parameters.Add(new OracleParameter("p_WARRANTYENDDATE", OracleDbType.Date));
command.Parameters["p_WARRANTYENDDATE"].Value = Convert.ToDateTime(AMCStartDateTextBox.Text).ToShortDateString();
even tried to pass it as string
string AD = Convert.ToDateTime(AMCStartDateTextBox.Text).ToShortDateString();
command.Parameters.Add(new OracleParameter("p_AMCSTARTDATE", OracleDbType.Varchar2));
command.Parameters["p_AMCSTARTDATE"].Value = AD;
Getting unterminated string constant error
I tried this below code & it works !!!!!!
string AMCStartDate = Convert.ToDateTime(AMCStartDateTextBox.Text).ToShortDateString();
command.Parameters.Add(new OracleParameter("p_AMCSTARTDATE", OracleDbType.Date));
command.Parameters["p_AMCSTARTDATE"].Value = AMCStartDate;

Send data from one page to another

I am trying to send form data from one page to another using C# ASP.Net. I have two pages default.aspx and default2.aspx.Here is the code I have in default.aspx:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Go"
PostBackUrl="~/Default2.aspx" />
<br />
From what I know so far the PostBackUrl is used to set the page in which you want the data to be sent is this correct?
Also how can I retrieve the data that is sent to Default2.aspx?
You have a few options, consider
Session state
Query string
Session state
If you are going to send data between pages, you could consider the use of Session State.
ASP.NET session state enables you to store and retrieve values for a
user as the user navigates ASP.NET pages in a Web application. HTTP is
a stateless protocol. This means that a Web server treats each HTTP
request for a page as an independent request. The server retains no
knowledge of variable values that were used during previous requests.
ASP.NET session state identifies requests from the same browser during
a limited time window as a session, and provides a way to persist
variable values for the duration of that session. By default, ASP.NET
session state is enabled for all ASP.NET applications.
Best of all, it is easy!
Put data in (for example on default1.aspx)
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Get it out (for example on default2.aspx)
string firstname = Session["FirstName"] // value of FirstNameTextBox.Text;
string lastname = Session["LastName"] // value of LastNameTextBox.Text;
Query string
If you are sending small amounts of data (eg id=4), it may be more practical to use query string variables.
You should explore the use of the query string variables, e.g.
http://www.domain.com?param1=data1&param2=data2
You can then get the data out like
string param1 = Request.QueryString["param1"]; // value will be data1
string param2 = Request.QueryString["param2"]; // value will be data2
You can use something like How do you test your Request.QueryString[] variables? to get the data out.
If you are unfamiliar with querystring variables check out their wikipedia article
Session variables can be useful in this context.
Foe example suppose your textboxes contain login credentials, then save them in sessions so that you can later use them in any other page. Like this:
In Button_Click-
Session["name"]=TextBox1.Text;
Session["pwd"]= TextBox2.Text;
Instead of PostBackUrl="~/Default2.aspx" you can write the following-
//in button click
Server.Transfer("~/Default2.aspx");
In Default2.aspx page load:
string a= Session["name"].ToString();
string b= Session["pwd"].ToString();
Try this in the Page_Load of Default2.aspx.
if (PreviousPage != null)
{
if (((TextBox)PreviousPage.FindControl("TextBox1")) != null)
{
string txtBox1 = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
Response.Write(txtBox1);
}
}
And yes you are correct, the data from page 1 will be sent to page 2 if you use the PostBackUrl attribute.
MSDN link
While all the answers here will work some aren't the most efficient. Why would a simple/standard http POST have to invoke (expensive) server-side Sessions?
Your code isn't doing anything special - it is simply POSTing a form to another page. All you need to do to obtain the POSTed data is go through the Request.Form collection.
Prior to the availability to set the PostBackUrl (if memory serves version 1 of asp.net), Server.Transfer and getting references to the previous page was how cross-page POSTing was done/documented. However, with PostBackUrl, things go back to basics, the way it should be - a standard http POST from one resource to another.
Here's a similar SO thread that maybe helpful.
another way is to save the data on a database and fetch it back on the other page:
//update
string query = "UPDATE table SET col = 'a'";
SqlCommand command = new SqlCommand(query, connection);
command.ExecuteScalar();
//select
string query = "SELECT col FROM table";
SqlCommand command = new SqlCommand(query, connection);
string value = command.ExecuteScalar();

Keep the text of the text box through a PageLoad();

I am wondering How i can keep the text of my textbox even if i have to make a new page load, clicking on an hyperlink.
It's always an empty string.
Can someone help me ?
lkForgotten.NavigateUrl = string.Format("Logon.aspx?forgotten={0}", "");
lkSend.NavigateUrl = string.Format("Logon.aspx?forgotten={0}&userEmail={1}", "submited", txtForgotten.Text);
try
{
if (Request.QueryString["forgotten"].ToString() == "")
{
txtForgotten.Visible = true;
lkSend.Visible = true;
}
if (Request.QueryString["forgotten"].ToString() == "submited")
{
userEmail = txtForgotten.Text;
SendForgottenPassword(userEmail);
}
}
catch { }
If you need to persist some data specific to the person, you can use a session. It is precisely the thing you need.
You can set it whenever you want and get the values you need.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Edit:
To satisfy some objections raised in comments, if the session itself isn't enough, you can still use a different approach. Monitor the textboxes with javascript and if their value is changed, add a cookie (or add a value to existing cookie, depends on the needs). Still much better approach than using querystring for this type of functionality... At least in my opinion.
Edit
Do the redirection with the
Javascript code
function redirect()
{
var val = document.getElementById('<%= txtForgotten.ClientID %>').value;
location.href='Logon.aspx?forgotten=submitted&userEmail=' + val ;
}
<input type="button" VALUE="Visit Microsoft" OnClick="redirect();">
problem witht he above code is when you are creating the url of forget password on page load at that time textbox value is empty and when do redirection by clicking forget password link its getting empty value only rather what you typed in your code...so to make it work do the redirection using javascript as above or make use of click event that do the redirection for you....
Org
following line change like this
if (Request.QueryString["forgotten"].ToString() == "submited") {
userEmail = txtForgotten.Text = Request.QueryString["userEmail"].ToString() ;
SendForgottenPassword(userEmail);
}
so when you are clicking button it get the value of userEmail from the querystring and restore value in you textbox ...this will surely do your task
or
you can make use of other client side mecanisam like cookies to store the value and than retrive it back on page...
serverside option is session variable also helpfull if you want to store the value and retrieve it back.....

Correct way to handle Caching of DB-Data

I always wondered how exactly you'd handle caching of database-values (in C#, ASP.NET) so you e.g. don't reload several DataSource-Bound ASP-Controls or don't have to reload them everytime you use a certain backend method.
Let's just take the following example:
aspx.cs-File:
List<FormElement> elements = FormElement.GetForForm(Session["FormName"].ToString());
Backend-Method:
public static List<FormElement> GetForForm(string fName)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select Rank, Control, Variable from inspire.dbo.formelement where formid=(select id from inspire.dbo.form where name=#name)", Database.Conn);
cmd.Parameters.Add(new SqlParameter("#name", fName));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt.Rows.ToList<FormElement>(item => new FormElement(item));}
How exactly would I handle caching here?
Thanks,
Dennis
what we have done for the caching:
in page side, use a global container (eg. dataset) to store all the required data, each data add a time flag for it
in backend side, use a same container to store the data, and also with the time flag
when page refresh, compare the time flag with current datetime, get data from that container;
or send a refresh_fetch to backend side, backend will get data from db and update caching content for its container, then send back the updated data to page
page update its container and display out
the flow is simply like this, however, based on real situation, the container, the refresh strategy... maybe different

Categories