ASP.NET UserControl get property in inline code - asp.net

I have a user control, in the page load of the control I am doing this :
if (ViewState["Lib"] != null)
{
cfg.Lib = (string)ViewState["Lib"];
}
This Lib property can be modified with a textbox like this :
protected void Lib_e_Changed(object sender, EventArgs e)
{
cfg.Lib = Lib_e.Text;
ViewState["Lib"] = Lib_e.Text;
}
I have written the following javascript in my ascx file :
alert('<%= cfg.Lib %>');
It will always return the default value even if I have changed the text in my textbox. My textbox is in an update panel and I have set AutoPostBack to true. Is there something I am missing to update my value ?

It is happening because aspx page render
alert('<%= cfg.Lib %>');
before any assign you are performing on
cfg.Lib
to make it workable what you can do is .. register the script from server side like
protected void Lib_e_Changed(object sender, EventArgs e)
{
cfg.Lib = Lib_e.Text;
ViewState["Lib"] = Lib_e.Text;
ScriptManager.RegisterStartupScript(updatePanelId, updatePanelId.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
//Page.ClientScript.RegisterStartupScript(this.GetType(),"AnyKey","alert('"+cfg.Lib +"')",true);
}

Related

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net

Open link in a new window in ajax panel on server side

I have asked this question before, but got no answer that worked.
This is a buttonclick event that should initiate the download:
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
SendFileDownload(file);
}
One of the solutions that was offered was opening a link in a new window and have the window on page load initiate the download there with this piece of code:
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
// SendFileDownload(file); dont call it here , call it in the other window
string url = "PopupFileDownload.aspx?file="+file;
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
}
This did not work. I tried doing something similar since I am using the Telerik Ajax Panel
ajaxPanel.ResponseScripts.Add("window.open('DownLoadPopup.aspx?file='" + file + "'', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');");
But this also did not work. the command was executed with no effect.
How can I send a file to the user without sacrificing the Ajax panel?
If your button's inside an ASP.NET Ajax UpdatePanel you could turn off the ajax for just the download button
ScriptManager.RegisterPostBackControl(btnDownload);
If you're using Telerik Ajax controls, you can use the following code to pop up a RadWindow.
Make sure you've got a RadScriptManager and a RadAjaxManager on your page before your RadAjaxPanel...
Then add a RadWindowManager inside your RadAjaxPanel like this...
<telerik:RadWindowManager runat="server" ID="rwm" Modal="true" Skin="Default" AutoSize="true" />
Then in your code, you can do this...
protected void btnDownload_Command1(object sender, CommandEventArgs e)
{
GridDataItem item = gvClients.Items[Convert.ToInt32(e.CommandArgument)];
GetUserData usr = new GetUserData(item["id"].Text, Security.level.Agent, servermap);
string file = usr.RetrieveContractPath();
rwm.Windows.Clear();
var rWin = new RadWindow();
rWin.ID = "Name of my window";
rWin.NavigateUrl = string.Format("~/DownLoadPopup.aspx?file={0}", file);
rWin.Width = Unit.Pixel(1000);
rWin.Height = Unit.Pixel(600);
rWin.VisibleOnPageLoad = true;
rwm.Windows.Add(rWin);
}
Adjust the path to your DownLoadPopup.aspx and the properties of the RadWindow as necessary.

AjaxControlToolkit AsyncFileUpload - how to modify a label text value in UploadedComplete event

I am trying to set a label text value after a file is uploaded to the server using a AsyncFileUpload component in AjaxControlToolkit. But it seams it is ineffective, although the file uploader is green after the upload, and the upload works.
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename);
sourceLabel.Text="saved to "+filename; //this has no effect. I assume this is because the event is Async, but how can I set the value of sourceLabel?
}
The AsyncFileUpload control uses hidden frame for file submitting so all updates of controls will be lost. Check this link and draw attention how the uploadResult label's text changed from AsyncFileUpload1_UploadedComplete method: Ajax Control Toolkit source code
It works for me: https://stackoverflow.com/a/12472235/2247978
.....................................................................................................
Add HiddenField control onto a form:
<asp:HiddenField runat="server" ID="UploadedPathHiddenField" />
Rewrite UploadComplete method as below:
protected void UploadComplete(object sender, AsyncFileUploadEventArgs e)
{
var fileName = GeneratePrefixFileName() + System.IO.Path.GetFileName(e.FileName);
var relativePath = "~/Image/" + fileName;
var filePath = Server.MapPath(relativePath);
AsyncFileUpload1.SaveAs(filePath);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "filePath", "top.$get(\"" + UploadedPathHiddenField.ClientID + "\").value = '" + ResolveClientUrl(relativePath) + "';", true);
}
After that you can get path of saved image in showConfirmation method by :
var src = $get("<%= UploadedPathHiddenField.ClientID %>").value;
.....................................................................................................
protected void BtnUpload_Click(object sender, EventArgs e)
{
UploadMessage.Text = UploadedPathHiddenField.Value;
}

ASP.net : textChange Partial Update for programmatically inserted textboxes

I trying get some programmatically inserted textboxes (inserted into a gridview) to do a textChange partial update. It is sort of working but it does not automatically calls textEntered() method after I typed some text in these textboxes. I got a clue that I might need to use AJAX and things like updatepanels but I just don't fully understand how they will work in the context of what I am trying to do.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (!e.Row.Cells[4].Text.Equals(" ") && firstTime == false)
{
TextBox tb = new TextBox();
tb.Text = e.Row.Cells[4].Text;
tb.TextChanged += new EventHandler(textEntered);
textBoxArray.Add(tb);
int length = textBoxArray.Count - 1;
tb = (TextBox)textBoxArray[textBoxArray.Count - 1];
e.Row.Cells[4].Text = null;
e.Row.Cells[4].Controls.Add(tb);
Cache["textBoxArray"] = textBoxArray;
} firstTime = false;
}
protected void textEntered(object sender, EventArgs e)
{
lbl_test.Text += "test";//This line is for testing purposes
}
auto postback of textbox is true or false? make it true.

Call a button_click on page_load asp.net

I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.

Resources