I have a LinkButton on my Page1.aspx with the fields
Attached below is the image of page1.aspx. And a gridview in Page2.aspx.. When i click onto the linkbutton , the page redirects to Page2.aspx and fill the gridview with the required fields..
where the Required Fields are
Image,
Name = Black Cap,
Title = Topi,
Price = 1200
The Code of Page1.aspx:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Dictionary<string, string> OrderDict = new Dictionary<string, string>();
if (e.CommandName == "orderClick")
{
string value = e.CommandArgument.ToString();
string id = this.ListView1.DataKeys[e.Item.DataItemIndex].Value.ToString();
OrderDict.Add(id, value);
Session["Order"] = OrderDict;
Response.Redirect("Page2.aspx");
Response.Write(OrderDict);
}
}
The Code of Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> Dictionary = (Dictionary<string, string>)Session["Order"];
//Regex reg = new Regex(#"\[([^\]]+)\]([^\[]+)");
if (Dictionary != null)
{
GridView1.DataSource = Dictionary;
//Dictionary = reg.Matches(Dictionary.ToString()).Cast<Match>().ToDictionary(x => x.Groups[1].Value
// , x => x.Groups[2].Value.Trim());
//string slit = Dictionary.s
this.GridView1.DataBind();
//this.GridView1.DataSource = Dictionary;
Response.Write(Dictionary.Values.Count);
}
}
This is the first time I see code that binds to a dictionary. You should bind to the Keys property of the dictionary.
// Change your original line in Page_Load to this... The variable name conflicts with the class name
Dictionary<string, string> orderDictionary = (Dictionary<string, string>)Session["Order"];
// Bind like this:
GridView1.DataSource = orderDictionary.Keys;
See Dictionary(Of TKey, TValue).Keys Property
Have you considered creating a class that represents the list of items you're storing in the Session? For example:
public class SelectedOrder
{
public string ID { get; set; }
public string Value { get; set; }
}
// Then in your ListView ItemCommand in Page1.aspx
var orders = ((List<SelectedOrder>)Session["Order"]) ?? new List<SelectedOrder>();
orders.Add(new SelectedOrder() { ID = id, Value = value });
Session["Order"] = orders;
// And in Page2
List<SelectedOrder> orders = (List<SelectedOrder>)Session["Order"];
if (null != orders) {
GridView1.DataSource = orders;
GridView1.DataBind();
// Rest of code follows...
}
I think this will be an easier approach to deal with in your code.
Related
I have a table called T_Score and the column called Team1, it has some stored values and I want these values to be added and displayed on a label.
This is the code which stores the values in the table:
private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new LeaderBoard());
SqlConnection conne = new SqlConnection(#"Data Source=LAPTOP-S2J1U9SJ\SQLEXPRESS;Initial Catalog=Unit4_IT;Integrated Security=True");
conne.Open();
string insertQuery = "insert into T_Score(Team1) " +
"values(#Team1)";
SqlCommand com = new SqlCommand(insertQuery, conne);
com.Parameters.AddWithValue("#Team1", txt_score4_tm1.Text);
com.ExecuteNonQuery();
conne.Close();
}
This code stores the value that needs to be added with the previous value.
Use the following query select sum(Team1) from T_Score; and instead of cmd.ExecuteNonQuery(); use cmd.ExecuteScalar(); and use the return value of the method ExecuteScalar
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar
Like this:
private void WriteToLabel()
{
using (SqlConnection conne = new SqlConnection(#"Data Source=LAPTOP-S2J1U9SJ\SQLEXPRESS;Initial Catalog=Unit4_IT;Integrated Security=True"))
{
conne.Open();
string selectQuery = "select sum(Team1) from T_Score;";
using (SqlCommand com = new SqlCommand(selectQuery, conne))
label1.Content = Convert.ToString(com.ExecuteScalar());
}
}
The line
label1.Content = Convert.ToString(com.ExecuteScalar());
Will require a Label called label1 for it to work.
It tries to write the result of Convert.ToString(com.ExecuteScalar()) into the Content property of said Label.
You can also use a TextBlock and than use the Text Property, so this line:
textBlock1.Text = Convert.ToString(com.ExecuteScalar());
Notice instead of calling conne.Close(); manually, I wrapped the SqlConnection conne into a using Statement, this should always be done with objects that inherit from IDisposable.
You can read about IDisposable and the using statement here:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
https://learn.microsoft.com/en-us/dotnet/api/system.idisposable
https://stackoverflow.com/a/61131/2598770
If you have the values already in a IEnumerable object eg. List<int> than you can just do the following
With a simple loop:
var myValues = new List<int>() { 1, 2, 3, 4, 5, 6 }; //<- list with temporary data
var sumOfValue = 0;
foreach (var myValue in myValues)
sumOfValue += myValue;
With LINQ:
var myValues = new List<int>() { 1, 2, 3, 4, 5, 6 }; //<- list with temporary data
var sumOfValue = myValues.Sum();
If you don't have an IEnumerable of int but instead a class than your code will look like this
public class MyValue
{
public int Value { get; set; }
//other properties
}
var myValues = new List<MyValue>()
{
new MyValue() { Value = 1 },
new MyValue() { Value = 2 },
new MyValue() { Value = 3 },
new MyValue() { Value = 4 },
new MyValue() { Value = 5 },
new MyValue() { Value = 6 },
}; //<- list with temporary data
With a simple loop:
var sumOfValue = 0;
foreach (var myValue in myValues)
sumOfValue += myValue.Value;
With LINQ:
var sumOfValue = myValues.Sum(x => x.Value);
In all those cases you will have to write sumOfValue into your Label or TextBlock like this
//Label
label1.Content = sumOfValue.ToString();
//or TextBlock
textBlock1.Text = sumOfValue.ToString();
To pass a value to a different page, all you would need to do is the following.
Search for your page in code behind eg. LeaderBoard.
It should look something like this
public partial class LeaderBoard : Page
{
//stuff...
}
Add a new Property to this class
public partial class LeaderBoard : Page
{
public int MyProperty { get; set; }
//stuff...
}
When you initialize the LeaderBoard eg. here
this.NavigationService.Navigate(new LeaderBoard());
Change the initialization to this:
this.NavigationService.Navigate(new LeaderBoard() { MyProperty = 7187, });
7187 is a random number this needs to be filled with what ever you need.
With this you have "transfered" data to LeaderBoard and the new property with its value can be accessed in LeaderBoard eg. there could be a method like this
public void Foo()
{
textBlock1.Text = Convert.ToString(this.MyProperty);
}
The class would than look like this:
public partial class LeaderBoard : Page
{
public int MyProperty { get; set; }
//stuff...
public void Foo()
{
textBlock1.Text = Convert.ToString(this.MyProperty);
}
}
If you need to change the MyProperty from a different place while the LeaderBoard is open keep the reference you have created.
To keep the reference change this line
this.NavigationService.Navigate(new LeaderBoard() { MyProperty = 7187, });
To this
_leaderBoard = new LeaderBoard() { MyProperty = 7187, };
this.NavigationService.Navigate(_leaderBoard);
And create a Field in the outer scope like this
private LeaderBoard _leaderBoard; //<- needs to be outside the method
private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
_leaderBoard = new LeaderBoard() { MyProperty = 7187, };
this.NavigationService.Navigate(_leaderBoard);
}
If Btn_LeaderB_Click gets called multiple times but you only want to create 1 LeaderBoard you can do this:
private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
if (_leaderBoard == null)
_leaderBoard = new LeaderBoard() { MyProperty = 7187, };
this.NavigationService.Navigate(_leaderBoard);
}
With that the _leaderBoard field will only get initialized once.
If you want to increase the value MyProperty everytime the Btn_LeaderB_Click method gets called you can further extend it to this:
private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
if (_leaderBoard == null)
_leaderBoard = new LeaderBoard() { MyProperty = 7187, };
else
_leaderBoard.MyProperty += int.Parse(txt_score4_tm1.Text);
this.NavigationService.Navigate(_leaderBoard);
}
I am writing a SharePoint app. There I have page with drop down list. I have
a handler for SelectedIndexChanged. I want to get the selected value but as CustomObject and the only option I see is string. I tried SelectedValue and it is still string.
That's how I set the list:
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = //retrieving data
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x});
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
And that's one of the ways I tried:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var index = groupingDropDownList.SelectedIndex;
CustomObject obj = (CustomObject)myDropDownList.Items[index].Value;
obj.DoSomething();
}
Is it even possible? Or do I have to have somewhere Dictionary with with objects?
You will want to leverage the html5 data attributes that you can then place onto the dropdown options. Here is an example of what you could do with your data.
// add Agencies' addresses as HTML5 data-attributes.
var agencies = agencyNames.ToList();
for (int i = 0; i < requesting_agency.Items.Count - 1; i++) {
requesting_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
servicing_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
}
Then when processing the information you could do something like so.
var index = groupingDropDownList.SelectedIndex;
var selectedText = myDropDownList.Items[index].SelectedValue;
var selectedValue = myDropDownList.Items[index].Attributes["attribute"];
// put into obj
// do something with object
Let me know if you have any questions.
You 're binding a object (x => new { x.Name, Value = x}) to dropdown value, you should bind actual value to it.
Test demo:
public class CustomObject
{
public int ID { get; set; }
public string Name { get; set; }
public CustomObject(int _ID,string _Name)
{
this.ID = _ID;
this.Name = _Name;
}
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = new List<CustomObject>();
customList.Add(new CustomObject(1,"test1"));
customList.Add(new CustomObject(2,"test2"));
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x.ID });
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
}
I am trying to add some controls to a list but for some reason its only saving the last view to the db.
public List<tblPortalIandEValue> createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_iandevalues.Add(new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
return _iandevalues;
}
I think my problems lies in my save cause I'm calling this list add new and then returning it think I should be returning the record instead
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues=_dal.createIandERecord(_customerId , "mortagecic", mortagecic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString());
_iandevalues.ForEach(n =>_dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}
Your problem is in your createIandERecord method since you are renewing the list everytime. change your code to this:
public tblPortalIandEValue createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
return new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
}
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues.Add(_dal.createIandERecord(_customerId, "mortagecic", mortagecic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString()));
_iandevalues.ForEach(n => _dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}
I currently have two list boxes. One is to store the key and the second is to view the list associated with it.
The following code I have displays the key in the first listBox but fails to show the list in the second:
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
I have checked using the debugger to make sure that there is data contained in the dictionaries list so I am not sure what the problem is.
Can anyone point out where I maybe going wrong?
Thanks
Lists of 'naked' strings can't be used as a DataSource. You need to wrap them in a simple class with a real property. See here
After you have declared a simple string wrapper class:
class aString { public string theString { get; set; }
public aString(string s) { theString = s; }
public override string ToString() {return theString;} }
you can either change your Dictionary to contain a List<aString> or you can create a List<aString> from your Dictionary Values:
List<aString> aStringList = dict [src].Select(item => new aString(item) ).ToList();
listBoxDST.DataSource = aStringList ;
The ListBox can now display the aString.ToString() values.
try this man
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
}
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
I have a situation that is pretty simple, and I'd like to know the ideal way to do it.
I have a combo box. Each line of the combo box corresponds to a particular strategy object.
What is the proper way to map the combo box lines to the strategy object.
The way I was doing it seems overly complicated, and I'm pretty much guaranteed there is a simple standard way to do this.
Thank you.
EDIT:
I had the data in a Dictionary, where the string was the text for the combobox, and the object was the strategy... But this isn't ordered... And I just know there is some extremely simple way to do it.
SOLUTION:
I used this solution, not feeling comfortable putting presentation logic in the data classes:
private partial class HtmlTransformState : AbstractHtmlEditFormState
{
private Dictionary<string, ITransformStrategy> strategies = new Dictionary<string, ITransformStrategy>()
{
{ "Simple URL", new TransformStrategy<SimpleUrlCodeExtractor>() },
{ "Overview", new TransformStrategy<OverviewCodeExtractor>() },
{ "Video List", new TransformStrategy<VideoListCodeExtractor>() },
{ "Video List No MbORKb", new TransformStrategy<VideoListNoMBOrKBAndNoLinksAllowedCodeExtractor>() },
{ "Blue Mountain 2007", new TransformStrategy<BlueMountain2007CodeExtractor>() },
{ "Four Gates", new TransformStrategy<FourGatesCodeExtractor>() },
{ "General", new TransformStrategy<GeneralCodeExtractor>() }
};
public override void DrawForm()
{
// ...
ParentForm.cmboTransformStrategy.DataSource = new BindingSource(strategies, null);
ParentForm.cmboTransformStrategy.DisplayMember = "Key";
ParentForm.cmboTransformStrategy.ValueMember = "Value";
}
public override IEnumerable<string> ProcessHtml(string urlPath)
{
ITransformStrategy transformStrategy = (ITransformStrategy)ParentForm.cmboTransformStrategy.SelectedValue;
// Do some stuff with 'transformStrategy'
}
}
Do you mean something like the following?
public class Strategy
{
private string _name = "default";
public string Name
{
get { return _name; }
set { _name = value; }
}
public Strategy(string name)
{
_name = name;
}
}
Then in form load (you need to have a combo box on that form):
private void Form1_Load(object sender, EventArgs e)
{
List<Strategy> ls = new List<Strategy>();
ls.Add(new Strategy("First"));
ls.Add(new Strategy("Second"));
ls.Add(new Strategy("Third"));
comboBox1.DataSource = ls;
comboBox1.DisplayMember = "Name";
}
Override ToString for your strategy object. After that you can insert your strategy objects directly in the combo box.
public class StrategyObject
{
public override string ToString()
{
return "return the text to display";
}
}
StrategyObject selectedStratObj = comboBox1.SelectedItem as StrategyObject;
I would use the SelectedIndexChanged event on the combobox and select the corresponding dictionary entry
found that, Bind a Dictionary to a ComboBox see below for a working example(at least on the original vb.net code that I wrote)
Vb.net converted into C#, you will have to manage the handle yourself
public class Form1
{
private Dictionary<int, myDic> dict = new Dictionary<int, myDic>();
private void // ERROR: Handles clauses are not supported in C#
ComboBox1_SelectedIndexChanged(System.Object sender, System.EventArgs e)
{
KeyValuePair<int, myDic> curItem = (KeyValuePair<int, myDic>)ComboBox1.SelectedItem;
MessageBox.Show(curItem.Value.myvalue);
}
private void // ERROR: Handles clauses are not supported in C#
Form1_Load(object sender, System.EventArgs e)
{
myDic d = default(myDic);
for (int i = 0; i <= 10; i++) {
d = new myDic();
d.myKey = i.ToString;
d.myvalue = Strings.Chr(65 + i);
dict.Add(d.GetHashCode, d);
}
ComboBox1.DataSource = new BindingSource(dict, null);
ComboBox1.DisplayMember = "value";
ComboBox1.ValueMember = "Key";
}
}
class myDic
{
public string myKey;
public string myvalue;
public override string tostring()
{
return myvalue;
}
}
Here's one of my finest innovations. :) I'm really proud of this little one.
public class Stringable<T>
{
private T _obj;
private Func<T, string> _convertFn;
public Stringable(T obj, Func<T, string> convertFn)
{
_obj = obj;
_convertFn = convertFn;
}
public T GetObj() { return _obj; }
public override string ToString() { return _convertFn(_obj); }
}
This generic class adds ToString() to any class (even a black-box class) and you can define its behavior inside the lambda. Imagine you have a class Person with properties FirstName and LastName. Here's how you would use it to populate Combo box.
_cboPersons.Items.Add(new Stringable<Person>(person,o=>string.Format("{0}, {1}", o.LastName, o.FirstName)));
Then, when combo box item is selected just use this to get the original object from your combo
Person person=(_cboPersons.SelectedItem as Stringable<Person>).GetObj() // Get's person object.