C# how to get HTML controls created dynamically - c#

I generated a HTMLTextArea using string and Response.Write():
string area = "<textarea id=\"myArea{0}\" cols=\"30\" name=\"S1\" rows=\"5\" runat=\"server\"></textarea>";
Response.Write(String.Format(area,1));
After this, I don't know how to get the object of this myArea1.
Are there any way I can achieve this goal?

The proper way to add System.Web.UI.HtmlControls. will be,
var newTextArea = new HtmlTextArea()
{
ID = string.Format("myArea{0}", 1),
Name = string.Format("S{0}", 1),
Cols = 30,
Rows = 5
};
Page.Controls.Add(newTextArea);
Then you can access it like,
var myTextArea = Page.FindControl("myArea1") as HtmlTextArea;

You can try this.
HtmlTextArea txt = (HtmlTextArea)(Page.FindControl("myArea1"));
string value = txt.Value;
Refer to this.

You don't really need to access the TextArea object itself if you are only interested in getting the user input, which you should be able to find in Request.Form collection on form submission.

Related

How do you create dependent dropdown lists in excel using EPPLUS for C#?

I'm tinkering with generating excel files with EPPLUS / C#. I can create a dropdown list, that's not a problem. What I'm struggling to find an example of is how to create dependent dropdown lists (e.g., country, region)
Anyone done this?
Here's an example of just adding a dropdown:
var range = ExcelRange.GetAddress(1, 2, ExcelPackage.MaxRows, 2);
var val = ws.DataValidations.AddListValidation(range);
val.ShowErrorMessage = true;
val.Formula.Values.Add("US");
val.Formula.Values.Add("CA");
So what I'd like to do is have a region cell right next to the country, that of which is filtered based on the country selected.
I was able to do this using OFFSET, MATCH, and COUNTA excel functions. I watched this video and was able to implement Leila's solution Smart Dependent Dropdown lists in Excel. She walks through each excel function used. I followed along with my own sheet and I was able to implement into my code.
For example:
using (var package = new ExcelPackage("filename"))
{
var foodsSheet = package.Workbook.Worksheets.Add("Foods");
foodsSheet.Cells["A1"].Value = "Fruit";
foodsSheet.Cells["A2"].Value = "Apple";
foodsSheet.Cells["A3"].Value = "Orange";
foodsSheet.Cells["A4"].Value = "Banana";
foodsSheet.Cells["B1"].Value = "Veggies";
foodsSheet.Cells["B2"].Value = "Lettuce";
foodsSheet.Cells["B3"].Value = "Tomato";
foodsSheet.Cells["B4"].Value = "Onion";
var dataList = foodsSheet.DataValidations.AddListValidation("D1");
dataList.Formula.ExcelFormula = "$A$1:$B$1";
var dependentList = foodsSheet.DataValidations.AddListValidation("E1");
//This is where the video comes in handy.
dependentList.Formula.ExcelFormula =
"OFFSET($A$1,1, +
MATCH($D$1,$A$1:$B$1,0)-1, +
COUNTA(OFFSET($A$1,1, +
MATCH($D$1,$A$1:$B$1,0)-1,5,1)),1)"
package.Save()
}
I hope this helps!

C# Selenium - dropdown menu/ combobox

I have a problem selecting from a custom dropdown menu.. I have tried both by using the XPath, CssSelector and Id.
I have added a link to the code here:
Picture of the code
I think i have to access the div class="SelectBox" in order to access the id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype'
but i keep getting errors.
This is what I'm currently trying but without any luck:
IWebElement test = driver.FindElement(By.XPath("//div[#class='input']//div[#id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype']"));
Can someone give me a clue on how to get access to the items in the dropdown?
Thank you! :)
You need to use "SelectElement" instead of "IWebElement".
SelectElement mySelect = new SelectElement(yourDriver.FindElement(By.Id("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype")));
mySelect.SelectByText("510111 Normalbehandling");
Try This
var select = driver.FindElementById("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype");
var stringValues = select.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, stringValues[0]);

How to get items from array element json c#

How do i get items from array element json c# ?
I want to get multiple artist names from my call, and put them in a listbox.
I can get the first artist like this etc.:
string url = #"http://api.musixmatch.com/ws/1.1/artist.search?apikey=key&q_artist=LMFAO&format=json";
string content = new WebClient().DownloadString(url);
dynamic artistData = JObject.Parse(content);
string artistName = artistData.message.body.artist_list[0].artist.artist_name;
But how can i get more of the names and put them in a listbox?
Here you can see how the json result looks like
Thanks in advance
You could try something like this
var artists = artistData.message.body.artist_list.Select(x => x.artist);
foreach (var artist in artists)
{
var artistName = artist.artist_name;
listBox.Items.Add(new ListBoxItem(artistName , artistName));
}
Hi you can use the below code snippet to get list of names
var artistNames = artistData.message.body.artist_list.Select(var=>var.artist.artist_name).ToList();
Then you could bind this list to your listbox either by using listbox.items.add function calls or by making use of ItemsSource property
Thanks for trying to help me, I really appreciate it. I figured out i could solve my problem like this:
var artistLength = artistData.message.body.artist_list.Count;
for (int i = 0; i < artistLength; i++)
{
var artistName = artistData.message.body.artist_list[i].artist.artist_name;
//printed in the console for testing
Console.WriteLine(artistName);
listBox1.Items.Add(artistName);
}

Binding BindingList<string[]> to datagridview

Situation:
I am attempting to bind a BindingList<string[]> constructed from a LINQ to SQL query to a DataGridView.
Problem:
I either cannot make modification to the DataGridView after items are generated -or- I get a bunch of unwanted fields in my DataGridView (it depends on which iteration of my code I use) I have googled as hard as I can and tried implementing most of the solutions I have found online to no avail.
I know that string has no public property for its actual value. I am having a difficult time determining how to retrieve that (I believe is part of the problem).
C#
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules
where p.ModuleName.Equals(clbModules.SelectedItem)
select p.ModuleId)
.FirstOrDefault();
BindingList<string[]> Data = new BindingList<string[]>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new string[] { p[0].ToString(), p[3].ToString() })
.ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
Unwanted Behavior:
This occurs after binding
Question:
Why is this happening?
How do I fix it?
Additional Information:
I am not sure what additional information may be need but I will supply what is requested.
Also if I switch to my other code iteration:
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules where p.ModuleName.Equals(clbModules.SelectedItem) select p.ModuleId).FirstOrDefault();
var Data = new BindingList<object>((from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers where p[2].Equals(item) select new {Question = p[0].ToString(), Answer = p[3].ToString() }).Cast<object>().ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
dgvQuestions.Columns[1].ReadOnly = false;
I can see the data properly but I cannot edit the column I would like to.
You are binding to a list of string arrays, and you are getting the properties form the array. Most likely you want something like the following:
var Data = new BindingList<object>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new {
Val1 = p[0].ToString(),
Val2 = p[3].ToString()
}).ToList());
The reason you're seeing those fields in the Grid is that you're binding each row to a string[]. So it is automatically displaying the properties of string[] as the columns. There is no built-in logic for the grid to parse an array and use the contents of the array as columns.
In order to get the DataGrid to display your data correctly, you should bind it to a custom type, and it will use the public properties of the type as columns.

Use an int when accessing a name in C#

I'm currently build a windows phone 8 application using c# and I'm wondering how I can achieve this:
for (int i = 1; i <= 18; i++)
{
_(i)Score.Text = "whatever here";
}
which when run should be something like:
_1Score.Text = "whatever here";
_2Score.Text = "whatever here";
_3Score.Text = "whatever here";
etc.
How am I able to achieve this as just putting _(i)Score doesn't work.
EDIT: What im doing is making a scorecard app which has a table overview. I've named each one as 1Socre, 2Score, 3Score etc. and I just want to update what they say. They are all textboxes and I'm just replacing the text inside.
Please Help.
Thanks
This most direct way to implement what you're doing:
var name = string.Format("_{0}Score", i);
this.Controls[name].Text = "...";
Knowing the types (based on #sa_ddam213's comment):
foreach(var textBox in Children.OfType<TextBox>().Where(txt => txt.Name.EndsWith("Score")))
{
textBox.Text = "...";
}

Categories