I have a several form elements that I am dynamically creating with javascript when a user changes a number value in a textbox, by filling the innerHTML of a div like so:
dfinnerhtml = dfinnerhtml + "<div class='field'> ";
dfinnerhtml = dfinnerhtml + "<textarea name='textbox1" + suffix + "' type='text' id='textbox1" + suffix + "' value='' rows='4' cols='20' class='field'></textarea> ";
dfinnerhtml = dfinnerhtml + "</div> ";
Then, in the aspx.vb code behind, when the user clicks the Save button, I run through a series of Requests to try and add the values that are in these form elements to a SQL string:
Dim DFTestValue1 As String
DFTestValue1 = Request("textbox" & c.ToString)
where c is a loop counter to the # of textboxes created (the input value mentioned above that triggers the create)
The problem here is that this code works in Internet Explorer but not in Firefox or Chrome. The Request() value returns null and nothing is saved. I hope I've explained this well enough.
This post has probably got the answer:
http://forums.asp.net/t/1235816.aspx
Try the PreviousPage property:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox pTextBox = (TextBox)PreviousPage.FindControl("TextBox1");
Response.Write("Previous Page TextBox: " + pTextBox.Text);
}
}
For anyone that is interested to know, the problem was that a stray tag closed a div that preceded the tag. Internet Explorer didn't seem to care and counted items beyond this point as part of the form.
Related
The following picture is view of one of my WebForms in project. I am currently facing following problem: I am loading CSV file, the program analyzes it and displays it as a Table. Then, using DropDownLists and Textboxes below, user chooses day, project and hours in order to decrease hours, which have been assigned to the project (imagine project x, which has budget of 100.000$ and has 150h to be burned by workers. Each worker burns his own hours and web admin can see how many hours can be burned and how does the budget look like). When I decrease hours for some day, for example project x, Monday, 8h- the page reloads and all the things, including table, dropdownlists and textboxes are closed and user add project hours for another days.
Please see the code that is responsible for changes in the database and is executed during Submit button click:
private void decreaseProjHours()
{
if (IsPostBack)
{
string nameOfProject = DropDownList1.SelectedValue;
int dayID = DropDownList2.SelectedIndex;
int hours = Convert.ToInt32(TextBox3.Text);
if ((nameOfProject == "") || (dayID > 7 || dayID < 0) || hours < 0)
{
Response.Write("You have entered invalid data in one of the fields!");
return;
}
//decreasing from total hours assigned to project
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WorkTimeDBConnectionString"].ConnectionString);
conn.Open();
string getTotalProjectH = "select hours from projects where project_name='" + nameOfProject + "'";
SqlCommand com = new SqlCommand(getTotalProjectH, conn);
int check = Convert.ToInt32(com.ExecuteScalar().ToString());
if (check - hours < 0)
{
Response.Write("No more hours can be reported for project" + nameOfProject);
conn.Close();
return;
}
else
{
try
{
string tryUpdate = "update projects set hours='" + (check - hours) + "'" + " where project_name='" + nameOfProject + "'";
SqlCommand com1 = new SqlCommand(tryUpdate, conn);
com1.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
conn.Close();
return;
}
}
}
}
Is is the problem with PostBack? I already tried making OnClientClick return false and Button3.Attributes.Add("onclick", "return false;")- the operation of modifying the database fails then and nothing is submitted.
What should I do? Is it really problem with PostBack or something else refreshes my webpage?
EDIT:
Button3.Attributes.Add("onclick", "return false;");
Button3.OnClientClick = "decreaseProjHours(); return false;";
Button3.UseSubmitBehavior = false;
Thanks in advance,
Kokos
You have more or less the correct code in the line
Button3.OnClientClick = "decreaseProjHours(); return false;";
However the problem is that it looks for a javascript function decreaseProjHours(), which I'm assuming you don't have since you have that method on the server side in your code behind. OnClientClick is by definition a client-side handler and so the method needs to be defined on the client side. Since it can't find the javascript function, it fails to execute the next line return false;.
If you need that code to execute first and then return false to prevent postback, you need to put the code in a javascript function instead of in the code-behind. You can then have that fuction either return true or false if you wish, instead of having the additional return statement in the OnClientClick definition.
Note that if you have a server-side click handler defined as well, this won't execute if there is no postback; i.e. the server-side OnClick handler only executes if the client side returns true.
I have a rather irritating and silly problem. I have a checkbox list on a asp page that I populate from a database. I am able to populate it, the problem lies when I do a specific check that checks if the users are active or not, it displays only the ones that are active but then leaves huge blanks in my control of where the original not active users were displayed.
I have pictures of before and after I implement that specific if statement:
here is the code for populating and checking:
this.AddMultipleUsers.Items.Clear();
foreach (GetAllLoginUsersResult result in from a in this.db.GetAllLoginUsers(null)
orderby a.FirstName
select a)
{
ListItem item = new ListItem();
string str = Membership.GetUser(result.UserId).ToString();
item.Text = result.FirstName.Trim() + " " + result.Surname.Trim() + " (" + str + ")";
if (!result.IsApproved)
{
item.Text = item.Text + " (Not Active)";
//item.Attributes.Add("style", "display:none;"); before
}
item.Value = result.UserId.ToString();
this.AddMultipleUsers.Items.Add(item);
}
in the first image, the checkboxlist is fully populated. Before link to code^
in the second after I un-comment this line //item.Attributes.Add("style", "display:none;");
then checkboxlist is the same size as the first image but, there is large spaces between
the users that are active, when you scroll down you see them randomly.
I want to remove the blank items within the checkbox list and make the other valid entries to be moved up like a normally populated checkbox list
Thank you
simply add a where condition to your select statement:
this.AddMultipleUsers.Items.Clear();
foreach (GetAllLoginUsersResult result in from a in this.db.GetAllLoginUsers(null)
orderby a.FirstName
where a.IsApproved==true
select a)
{
ListItem item = new ListItem();
string str = Membership.GetUser(result.UserId).ToString();
item.Text = result.FirstName.Trim() + " " + result.Surname.Trim() + " (" + str + ")";
item.Value = result.UserId.ToString();
this.AddMultipleUsers.Items.Add(item);
}
now you are only cycling through the active users, and no longer need to hide the inactive ones.
i want to know as how to search or filter records in a gridview dynamically based on the character(s) entered on a textbox. What is the best way to achieve this? Any sample codes or examples will be really helpful.
The trick here is to make databind only when the text change on the search box, but you must always set the datasource select command code. So you add a text box, and a button that say, submit, and you have the following:
OnPageLoad ->
if(SearchContron.Text.Length > 0)
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE Desc LIKE N'%" + SearchContron.Text +"%'"
else
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE "
and
OnSubmitButtonClick -> GridView.DataBind()
If you do it other way, the paging and editing and other commands will fail. You can also make it more advanced if you get the text from the text box and break it in many words and search each one as separate on the same sql command.
Its simple,
Look here for a basic tutorial on adding Ajax control to page.
1) Add the text box as well as the grid view into same update panel
2) In the text box's key press event, you can set the data source of gird and invoke databind command.
Note that when the key press will be fired, it will cause the complete page life cycle to be executed at server side. Hence, you will have to check whether the post back is async or not in your Page Load even handler.
A trick to reduce the number of database queries being fired is to set a timer when the user presses a key with a timeout of say...500ms and do the databinding of gridview in timer's tick event. If you do this, database will be queried only when the user has stopped typing something.
Thanks,
Vamyip
To bind gridview data write the following code
private void GridData()
{
string conString = ConfigurationManager.ConnectionStrings["MyCon"].ToString();
SqlConnection sqlcon = new SqlConnection(conString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
String query;
if (txtsearch.Text == "")
{
query = "select PersonID,LastName,FirstName from Person";
}
else
{
query = "select PersonID,LastName,FirstName from Person where PersonID like '" + txtsearch.Text + "%' or LastName like '" + txtsearch.Text + "%' or FirstName like '" + txtsearch.Text + "%'";
}
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
grdsearch.DataSource = dt;
grdsearch.DataBind();
}
else
{
grdsearch.DataBind();
Label1.Text = "No Records Found";
}
sqlcon.Close();
}
In page load event
if (!IsPostBack)
{
GridData();
}
for search button click event call GridData() method and
for clear button click event write following code
txtsearch.Text = "";
GridData();
Label1.Text = "";
Unless you have a specific need to do this on the server, why not perform the filtering on the client? A solution like DataTables is fast and user-friendly.
If you do other way to working search filtering condition for grid view header part. it is easy to use implement in your code. This is concepts used without database but i was using data table in linq. i hope to this code use full.
DataTable dt = (DataTable)Session["ProductTable"];
var query = from t in dt.AsEnumerable()
where t.Field<string>("ProducId").StartsWith(txtProductId.Text.ToString().Trim())
|| t.Field<string>("ProducId").Contains(txtProductId.Text.ToString().Trim())
select t;
Here is a sample program.
implement the onclick of search button like this:
protected void searchButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(searchTextBox.Text))
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
" ORDER BY [name], [id]";
}
else
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
"and "+DropDownList1.SelectedValue+" LIKE '%" + searchTextBox.Text + "%' ORDER BY [name], [id]";
}
GridView1.DataBind();
}
I have a page www.senderdomain.com/sender.aspx, from which i need to write a string to another page in other domain www.receiverdomain.com/receiver.aspx
In sender.aspx i have written
Response.Write("Hello");
Response.Redirect(Request.UrlReferrer.ToString());
It gets redirected to respective receiver.aspx page, but I am not sure how to get the text "Hello" in receiver.aspx page. Can any pl help on this?
It seems you have a value on Sender.aspx that you need to display in receiver.aspx. This is how you can do it.
//On Page_Load of sender.aspx
Session["fromSender"] = "Hello";
Respone.Redirect("receiver.aspx");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Session["fromSender"].ToString()))
Response.Write(Session["fromSender"].ToString());
EDIT
In case of change in domain, immediate easy way is to pass the value in query-string.
//On Page_Load of sender.aspx
Response.Redirect("http://www.receiverdomain.com/receiver.aspx?fromSender=Hello");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Request.QueryString["fromSender"].ToString()))
Response.Write(Request.QueryString["fromSender"].ToString());
You may observe that the code pattern remains the same and container that is used to transfer the value changes from Session to QueryString.
EDIT2
If security is a concern with you in this case and you don't wish to expose the value ["Hello"], then here comes another way that can help you. In this solution we will first redirect the page to receiver and then from receiver it shall ask for the value to sender. So first we'll write the code for receiver.
//On Page_Load of receiver.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Remember to use System.Net namespace
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://www.senderdomain.com/sender.aspx?cmd=getvalue");
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
//Remember to use System.IO namespace
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
Response.Write(fromSender);
Response.End();
}
}
And in the sender.aspx
//On Page_Load of sender.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["cmd"].ToString()))
{
string cmd = Request.QueryString["cmd"].ToString();
if (cmd.Equals("getvalue", StringComparison.OrdinalIgnoreCase))
{
Response.Clear();
Response.Write("Hello");
Response.End();
}
}
Response.Redirect("http://www.receiverdomain.com/receiver.aspx");
Response.End();
}
}
You need to pass the value in the url or post it in a cross page postback.
For secure cross domain communication, take a look at SAML (Security Assertion Markup Language). It is a standard way of passing information securely across domain boundaries. It is most often used in Single Sign On scenarios, but it can be used to pass data securely. Are you using certificates? What type of encryption are you using?
Another option would be to save state to a database or filesystem that is accessible to both domains.
pass data in query string because can not do like this
for example
Response.Redirect(Request.UrlReferrer.ToString() + "?mytext=hello");
And in receiver page access querystring data, will resolve your issue.
use private algorithm like
string message = "hello";
add 1 to each char so that hello become ifmmp
and on receiver side -1 from each char so it will be hello
The Response.Redirect method will scrap everything that you have written to the page, and replace it with a redirection page, so you can't send any content along with the redirect.
The only option to send data along in a redirect (that works between differnt domains and different servers) is to put it in the URL itself. Example:
string message = "Hello";
Response.Redirect(Request.UrlReferrer.ToString() + "?msg=" + Server.UrlEncode(message));
Another option is to output a page containing a form that is automatically posted to the destination:
string message = "Hello";
Response.Write(
"<html>" +
"<head><title>Redirect</title></head>" +
"<body onload=\"document.forms[0].submit();\">" +
"<form action=\"" + Server.HtmlEncode(Request.UrlReferrer.ToString()) + "\" method=\"post\">" +
"<input type=\"hidden\" name=\"msg\" value=\"" + Server.HtmlEncode(message) + "\">" +
"</form>" +
"</body>" +
"</html>"
);
Response.End();
You can use Request.Form["msg"] on the recieving page to get the value.
Don't use the built-in URL encode, if you want to avoid all sorts of problems later.
String UrlEncode(String value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~".IndexOf(symbol) != -1) result.Append(symbol);
else result.Append("%u" + String.Format("{0:X4}", (int)symbol));
}
return result.ToString();
}
The above supports unicode, and pretty much everything.
I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.
I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method).
protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}
On a postback, when the page loads is the view of the hidden field what was posted back or is it the value you set when the page loads? It may be that you have to worry about the case where in the postback you aren't resetting a value to what it was originally. Another point is that if you do a delete, are you refreshing the data that you show or is it the same? Those would be my suggestions.
When I do a postback the value is the same what was postedback. I think updatepanel wasnt refresh. I tried to do __doPostBack('UpdatePanel1',''), didnt work either.