ASP.NET Chart Click, Pass Data and in New Tab - c#

I am trying to get an asp.net chart and it's legend to allow me to open up another page in another tab passing the values of the piece of the chart I clicked on with it. I have been able to get it to open up another tab when clicking on the chart by doing the following but it does not pass the data.
Chart2.Series[0].LegendUrl = "chartdetails.aspx";
Chart2.Series[0].Url = "chartdetails.aspx";
Chart2.Series[0].LegendMapAreaAttributes="target=\"_blank\"";
Chart2.Series[0].LegendPostBackValue = "#VALY-#VALX";
Chart2.Series[0].MapAreaAttributes="target=\"_blank\"";
Chart2.Series[0].PostBackValue = "#VALY-#VALX";
If I leave out the urls and mapareaattributes I can then get it to go to the onclick where I am able to get the data, put it in a session variable and use Reponse.Redirect to open the new page where it sees the session variable data,however it doesn't open in another tab, it opens in the same tab.
Chart2.Series[0].LegendPostBackValue = "#VALY-#VALX";
Chart2.Series[0].PostBackValue = "#VALY-#VALX";
protected void Chart2_Click(object sender, ImageMapEventArgs e)
{
HttpContext.Current.Session["VAL"] = e.PostBackValue;
Response.Redirect("chartdetails.aspx", false);
}
How can I get it to do both? Does Response.Redirect have a way to open a new tab? Some research leads me to believe it does not. Is there a way to get both the server side onclick event to run, so I can set the session variable and the chart.series.url to fire after the server side click runs so the session variable would be set before I open the new tab?
I'm feeling like this may be a case of "I can't have my cake and eat it too."

As it turns out I can have my cake and eat it too. If I set the url, postbackvalues, and legendmapareaattributes in my Page_Load and set up the click for the chart to put the PostBackValue in the session variable when you click on the chart it saves the value in the session variable that is listed in the PostBackValue of the Series of the chart. It then opens in a new tab chartdetails.aspx where I can access the information from the session variable.
Chart2.Series[0].LegendUrl = "chartdetails.aspx";
Chart2.Series[0].LabelUrl = "chartdetails.aspx";
Chart2.Series[0].Url = "chartdetails.aspx";
Chart2.Series[0].LegendPostBackValue = "#VALY-#VALX";
Chart2.Series[0].LabelPostBackValue = "#VALY-#VALX";
Chart2.Series[0].PostBackValue = "#VALY-#VALX";
Chart2.Series[0].LegendMapAreaAttributes = "target=\"_blank\"";
Chart2.Series[0].LabelMapAreaAttributes = "target=\"_blank\"";
Chart2.Series[0].MapAreaAttributes="target=\"_blank\"";
protected void Chart2_Click(object sender, ImageMapEventArgs e)
{
HttpContext.Current.Session["VAL"] = e.PostBackValue;
}

I can't use postback to get the value on the series for some reason. So, I want to share my way inspired by #Adam that is loop over the series points after data binding the chart and set URL.
GET:
Series s=new Series("Test");
/*
* After Data bind to the series s
*/
for (int p = 0; p < s.Points.Count; p++)
{
s.Points[p].Url ="test.aspx?name1=value1&name2=value2";
s.Points[p].MapAreaAttributes = "target=\"_blank\"";
}
POST:
(I put javascript function in url. So, It will execute the javascript for me to send a form I created in the function to the text.aspx.)
Series s=new Series("Test");
/*
* After Data bind to the series s
*/
for (int p = 0; p < s.Points.Count; p++)
{
s.Points[p].Url ="javascript:(function(){" +
"var mapForm = document.createElement('form');mapForm.target = '_blank';" +
"mapForm.method = 'POST';mapForm.action = 'test.aspx';" +
"var mapInput = document.createElement('input');mapInput.type = 'hidden';" +
"mapInput.name = 'partID';mapInput.value = 'put any value you need';" +
"mapForm.appendChild(mapInput);document.body.appendChild(mapForm);" +
"mapForm.submit();document.body.removeChild(mapForm);})();";
}
Reference:
Javascript pass values using POST

Related

Dynamic Text Box Add on button click and data session in asp.net

QUESTION UPDATE
I am using this piece of code for cor adding multiple labels on button click.
But each and every time it gives count value 0 and after execution only same label comes.
int count = (int)ViewState["count"];
for (int i = 0; i <= count; i++)
{
TextBox txtnew = new TextBox();
txtnew.ID = "label_" + (i + 1);
txtnew.Text = "label_" + (i + 1);
ViewState["count"] = i;
pnlControl.Controls.Add(txtnew);
}
ViewState["count"] = count + 1;
What i want now is how to keep that data of each control binded to it in its more convenient way.
Dynamic controls are lost on every PostBack, so you need to keep track of the created ones somewhere and recreate them when the page is reloaded.
See my anwer here: How to dynamically create ASP.net controls within dynamically created ASP.net controls
It is about buttons but the basic principle is the same. Just replace Button with Label and it will work.
That's cause it's a web application and thus the session is not retained cause web applications are stateless in nature. So, every post back you get a new page instance which will have int count is 0. Solution: Use Session to store the data for future re-use like
int count = pnlControl.Controls.OfType<Label>().ToList().Count;
Session["count"] = count;
Retrieve it back on postback request
if(Session["count"] != null)
count = (int)Session["count"];

Retrieve Values from asp control in c# code behind

I have looked extensively to find an answer to this question but I only get extremely close. I have a web form that I use to add and edit records. When a record is selected in the gridview, a session variable is set and then used on page load to populate the text fields. If the session variable is not set, the form will be blank and the logic run as a new record. My problem is that I can add a new record successfully - I debugged and checked to make sure the asp controls passed the proper values to the code behind - but I cannot edit a record successfully. For some reason, the code behind file does not retrieve the proper values from the text boxes. Instead, it keeps the original populated values thus defeating the purpose of the edit. I imagine it is a binding issue but I am unsure and have searched upon end. Here is my code behind file:
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID
var id = Convert.ToInt32(Session["editID"]);
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = editRecipe.Recipe_ID.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Text = "Edit Record";
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
Recipe recipe = new Recipe();
dbCRUD newRecord = new dbCRUD();
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
//recipe.Recipe_ID = int.Parse(recordID.Text);
recipe.Name = addName.Text.ToString();
recipe.Meal = addTypeDDL.SelectedValue.ToString();
recipe.Difficulty = addDifficultyDDL.SelectedValue.ToString();
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text.ToString();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
recipe.Recipe_ID = Convert.ToInt32(Session["editID"]);
//If recordID exists, recipe will be passed to UpdateRecord method
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
Any object passed to my edit method is successful, however, as I mentioned, it does not grab the newly updated text box values.
Did you try checking PostBack property , Your code is loading the data everytime the page is posted back. So when you update the values in the form and hit update button. The Page_Load method is called first and it reloads all the data (replaces your updated values on the form) and then hit the update button event handler. So everytime your old values are being saved.
You may remove the code from page_load method and put it where you are setting the Session["EditId"] value. This will solve your problem.
I would suggest using a static dataset and bind it to the recordsource of the gridview control. Whenever you wanna edit a record update the dataset simultaneously and rebind it to the gridview control....hope that helps:)

Error When making a loop to crawl Google next page Watin

I have a simple code that help me crawl to page 2 of Google result page:
var ie= new IE();
ie.Link(Find.ByText("2")).Click();
All I want is crawling to more next page with the inputed number of page, so that I make a loop like this:
string[] page = null;
for (int i = 0; i < NumOfPage; i++)
{
Array.Resize<string> (ref page, i+1);
page[i] = "\"" + i.ToString() + "\"";
}
int count=2;
while (count<NumOfPage)
{
ie.Link(Find.ByText(page[count])).Click();
count++;
}
But the result is it pause at the first page, no crawling to the next page. It's seem the loop doesn't work. Where is the problem???
I think you should not use Click() method to go to the next page, I recognized that Click() will be performed only when the Link is visible, so you have to scroll the vertical scrollbar to the bottom to show the Link first (scrolling manually or programmatically works as you want). However I think to go to the next page, you can call the method GoTo() instead with the Url got from the found Link. I've tested it OK but the delay between page switches is a little large (about 2 seconds or above). I don't know why you want to do this and would like to know it from you:
for (int i = 2; i < NumOfPage; i++)
{
ie.GoTo(ie.Link(WatiN.Core.Find.ByText(i.ToString())).Url);//Don't need quotes at all.
}
:)
// Setup browser object
var browser = new IE();
var url = "www.google.com";
browser.GoTo(url);
var searchBox = browser.TextField(Find.ByName("q"));
searchBox.Value="Rex";
//click on the search button
var btnSearch = browser.Button(Find.ByValue("Search"));
btnSearch.Click();
//wait for browser to load properly
browser.WaitForComplete();
// Find the navigation menu table
var navigationtable = browser.Table(Find.ById("nav"));
// To go to the second page
var secondpage = navigationtable.Link(Find.ByText("2"));
secondpage.Click();
//wait for browser to load properly
browser.WaitForComplete();
this simply goes to the second page
now if you want to loop through
then
for (int i = 2; i <= 10; i++)
{
var nextpage = navigationtable.Link(Find.ByText("i"));
//check if the link exists
/if yes then click on it
if(nextpage.Exists)
nextpage.click();
browser.waitforComplete
}

Need help in understanding this error message that I'm getting

Please help me understand what is this error that I'm getting:
lblTabCounter is a label coded in the aspx page while the lblc[index] is a collection of label created at runtime during page load.
Declaration outside of page load:
Label[] lblc = new Label[10];
Inside Page Load Event:
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Inside another event called NodeChanged:
int TabCount = Convert.ToInt32(lblTabCounter.Text.ToString());
int TabIndex = Convert.ToInt32(lblTabCounterIndex.Text.ToString());
if(TabCount <= 10)
{
divcont.Visible = true;
string tabName = getURLName(uRL);
MenuItem myItem = new MenuItem(tabName, TabIndex.ToString());
Menu1.Items.AddAt(TabIndex, myItem);
//f1.Attributes["src"] = url;
f1.Attributes.Add("src", lblURL.Text.ToString());
MultiView1.ActiveViewIndex = TabIndex;
lblc[TabCount].Text = lblTabCounter.Text;
lblc[TabCount + 1].Text = lblURL.Text;
TabCount++;
TabIndex++;
lblTabCounter.Text = TabCount.ToString();
lblTabCounterIndex.Text = TabIndex.ToString();
tvPermissions.ExpandAll();
//tvPermissions.CollapseAll();
int i = ctr;
}
Note: This are all inside site.master.
The problem is your web page is refreshing and losing the state of the labels.
Label[] lblc = new Label[10];
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label();
this.Controls.Add(lblc[i]);
if (Session["lblc" + i.ToString()] == null)
Session["lblc" + i.ToString()] = lblc[i].Text = (i + 1).ToString();
else
lblc[i].Text = (string)Session["lblc" + i.ToString()];
}
Then when you want to set a label you use the following (when the page is not being refreshed by the event)
lblc[4].Text = "cool";
Session["lblc4"] = "cool";
However because your click event is refreshing the page it loses contact with the lblc so you only set the Session so upon refresh you will see your new Label. (when the page is being refreshed by the event)
Session["lblc4"] = "cool";
The page is in the process of refreshing as a result of your particular event so the label disappears but the session state remains so when you set the session upon refresh the code grabs the session instead of setting it to the default number.
Rather than change the text of the label when it refreshes you are actually generating the new label with the session string you set.
Also make sure you have <sessionState mode="InProc" /> in your Web.config file under <system.web>
Please read more on Session States here http://msdn.microsoft.com/en-us/library/87069683(v=vs.80).aspx
There are two possible issues with that line of code:
lblc[TabCount] is null.
lblTabCount is null.
Since you are paused in the debugger, you can see which of those is the case, then look around in the rest of the code to find out why.
I would follow the path of the lblc[index] array to determine if the element offset is within range as well as it being created properly and not ending up there as a null (whether the null being the object lblc[index] or the text property) being referenced.

How to get RadToolBarDropDown selected item value in c#

How to get the RadToolbarDropDown selected item value in code behind file. In my case I have a RadToolBar in which I dynamically create RadToolBarDropDown. I set these DropDown Value and Text dynamically as I my code shows.
RadToolBarDropDown dd = new RadToolBarDropDown();
if (ds.HasRows())
{
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
RadToolBarButton rtb = new RadToolBarButton();
rtb.Text = row["Description"].ToString();
rtb.Value = row["ProblemStatusID"].ToString();
rtb.CommandName = "StatusChange";
rtb.CommandArgument = row["ProblemStatusID"].ToString();
dd.Buttons.Add(rtb);
}
}
RadToolBarItem item = dd;
mlmToolBar.Items.Add(item);
Now I want to get selected item value in cs when command name "StatusChange" fire. I want to get the clicked value of the dropdown. How I can get the clicked dropdown value?
There are 2 ways you can handle the button click event of the dropdown items. You can handle it on server side or you can handle it on client side. Lets look at it one by one:
Server Side:
Assume I have a rad tool bar control on my page. Here is the code for the same:
<telerik:RadToolBar runat="server" ID="rtlMyToolBar"
OnButtonClick="rtlMyToolBar_ButtonClick" ></telerik:RadToolBar>
Note that I have handled the OnButtonClick event. We will look at it next.
From code behind I am adding a dropdown control and adding buttons to the drop down. Here is the code for the same:
RadToolBarDropDown dd = new RadToolBarDropDown("Drop Down - Handled Server Side");
RadToolBarButton rtb = new RadToolBarButton();
rtb.Text = "Bold";
rtb.Value = "Bold";
rtb.CommandName = "Bold";
rtb.CommandArgument = "Bold";
dd.Buttons.Add(rtb);
rtb = new RadToolBarButton();
rtb.Text = "Italic";
rtb.Value = "Italic";
rtb.CommandName = "Italic";
rtb.CommandArgument = "Italic";
dd.Buttons.Add(rtb);
rtb = new RadToolBarButton();
rtb.Text = "Underline";
rtb.Value = "Underline";
rtb.CommandName = "Underline";
rtb.CommandArgument = "Underline";
dd.Buttons.Add(rtb);
rtlMyToolBar.Items.Add(dd as RadToolBarItem);
Now lets take a look at the event handler:
protected void rtlMyToolBar_ButtonClick(object sender, RadToolBarEventArgs e)
{
var toolBarButton = e.Item as RadToolBarButton;
string commandName = toolBarButton.CommandName;
if (commandName == "YourCommandName")
{
//Your logic
}
}
Client Side:
Now lets take a look at how to listen to drop down button click on the client side. Here is the code snippet for the rad tool bar:
<telerik:RadToolBar runat="server" ID="rtlMyToolBar2"
OnClientButtonClicked="OnClientButtonClicked"></telerik:RadToolBar>
Note that now I am listening to OnClientButtonClicked event. The event handler is a javascript function reference.
Here is the javascript code:
<script>
function OnClientButtonClicked(sender, args) {
$("#status").append("OnClientButtonClicked: " + args.get_item().get_text() +
" - Command Name: " +
args.get_item().get_commandName() + "<br/>");
}
</script>
All telerik controls have a rich consistent client side and server side API.
Here is the GIST link for the above code: https://gist.github.com/lohithgn/5329716
Here is a example which show cases the client side api in our live demo site: http://demos.telerik.com/aspnet-ajax/toolbar/examples/clientside/clientevents/defaultcs.aspx
Here is the client side API basics help documentation:
http://www.telerik.com/help/aspnet-ajax/toolbar-clientsidetoolbaritem.html
Thanks

Categories