Field1 value --> variable name ; Field2 value --> variable value (C# code behind)

 I would like to add quantities to variables based on two fields in a table. 

The table includes two field names: ingredient, weight.  Assume a simple formulation: add 50 lbs water, add 20 lbs eggs, add 10 lbs water, add 5 lbs salt.

The table would have: 
water, 50
eggs, 20
water, 10
salt, 5
The variables water, eggs, water and salt have already been defined.  I want something that will cycle through and add the quantities (lbs) to the variable.  Ingredients can appear more than once in a formulation--notice that water appears twice and at the end there is 60 lbs.
Thank you for your help with this,
 -Larry
 
 

 


Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/3/2008 3:07:39 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

5 Replies
1473 Views

Similar Articles

[PageSpeed] 56

 If you just need simple key/value pair, you could use a System.Collections.Hashtable, which has a string key and an object value.  If you want a more type safe solution, you could use System.Collections.Generic.Dictionary<string, int>.

In both case, putting values in would be the same, but when getting values out of the Hashtable, you would have to cast them.

The keys for both of these can only be associated to one value.  You could try either a Pair (again, you would have to cast the values when you retrieve them) or make your own class like:

namespace MyApp
{
public struct Ingredient
{
public string Name;
public int Amount;
public Ingredient(string name, int amount)
{
Name = name;
Amount = amount;
}
}
}
Then use a List<Ingredient> for your datasource. 
using System.Collections.Generic;
List<Ingredient> recipe = new List<Ingredient>();
recipe[0] = new Ingredient("water", 50);
recipe[0] = new Ingredient("eggs", 20);
recipe[0] = new Ingredient("water", 10);
recipe[0] = new Ingredient("salt", 5);
 
0
ADavis
1/3/2008 4:14:29 PM

ADavis:
 If you just need simple key/value pair, you could use a System.Collections.Hashtable, which has a string key and an object value.  If you want a more type safe solution

 

If I understand correctly, when you mention wanting a more type safe solution, is that out of concern that someone might put text into a field entry that is supposed to have a numerical value, and vice versa?

Or is there some other concern?

Thank you,

-Larry


Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/3/2008 4:20:42 PM

Here is a sample web app:

ASPX SOURCE:

 

1    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_test_Collections_Default" %>
2    
3    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4    <html xmlns="http://www.w3.org/1999/xhtml">
5    <head runat="server">
6        <title>Untitled Page</title>
7    </head>
8    <body>
9        <form id="form1" runat="server">
10       <div>
11           <asp:Table ID="Table1" runat="server">
12               <asp:TableRow ID="TableRow1" runat="server">
13                   <asp:TableCell runat="server">Water</asp:TableCell>
14                   <asp:TableCell runat="server">50</asp:TableCell></asp:TableRow>
15               <asp:TableRow ID="TableRow2" runat="server">
16                   <asp:TableCell runat="server">Eggs</asp:TableCell>
17                   <asp:TableCell runat="server">20</asp:TableCell></asp:TableRow>
18               <asp:TableRow ID="TableRow3" runat="server">
19                   <asp:TableCell runat="server">Water</asp:TableCell>
20                   <asp:TableCell runat="server">10</asp:TableCell></asp:TableRow>
21               <asp:TableRow ID="TableRow4" runat="server">
22                   <asp:TableCell ID="TableCell1" runat="server">Salt</asp:TableCell>
23                   <asp:TableCell ID="TableCell2" runat="server">5</asp:TableCell></asp:TableRow>
24               <asp:TableRow ID="TableRow5" runat="server">
25                   <asp:TableCell ID="TableCell3" runat="server">Eggs</asp:TableCell>
26                   <asp:TableCell ID="TableCell4" runat="server">2</asp:TableCell></asp:TableRow>
27           </asp:Table>
28       </div>
29       <asp:Button ID="btnCommit" runat="server" onclick="btnCommit_Click" 
30           Text="Commit!" />
31       </form>
32   </body>
33   </html>
 

C# Code-Behind:

 

1    using System;
2    using System.Collections;
3    using System.Configuration;
4    using System.Data;
5    using System.Linq;
6    using System.Web;
7    using System.Web.Security;
8    using System.Web.UI;
9    using System.Web.UI.HtmlControls;
10   using System.Web.UI.WebControls;
11   using System.Web.UI.WebControls.WebParts;
12   using System.Xml.Linq;
13   using System.Collections.Generic;
14   
15   public partial class _test_Collections_Default : System.Web.UI.Page
16   {
17       Dictionary ingredients;
18   
19       protected void Page_Load(object sender, EventArgs e)
20       {
21           ingredients = new Dictionary();
22       }
23       protected void btnCommit_Click(object sender, EventArgs e)
24       {
25           // loop through the table and collect the ingredients
26           foreach (TableRow tr in Table1.Rows)
27           {
28               // get the values of the cells
29   
30               // first cell is string value
31               string type = ((TableCell)tr.Cells[0]).Text;
32               // second cell is int32 value
33               Int32 value = Int32.Parse(((TableCell)tr.Cells[1]).Text);
34   
35               // ensure not empty cells
36               if (type != string.Empty)
37               {
38                   // see if it is already in our dictionary
39                   if (ingredients.ContainsKey(type))
40                   {
41                       // already exists, so get the current value
42                       //int value = ingredients[type];
43                       // add it to the current value
44                       // put it into our collection
45                       ingredients[type] += Int32.Parse(tr.Cells[1].Text); ;
46                   }
47                   else
48                   {
49                       // doesn't exist, so add it
50                       ingredients.Add(type, value);
51                   }
52               }
53           }
54       }
55   }
 
"A common mistake that people make when trying to design something completely foolproof was to underestimate the ingenuity of complete fools." ~ Douglas Adams

http://pixelsyndicate.com/ps/
0
pixelsyndicate
1/3/2008 4:47:11 PM

I should have wrote that the table already exists and it is in a database.

I thought that would be assumed but I was incorrect, as I see from the two replies.

I apologize for not being more specific in the original question.

 

I think I can complete this if I use a while (reader.Read()) to cycle through what was selected in the table in the database.

I think I can use

thename = reader["ingredient"].ToString();

string stringvalue = reader["weight"].ToString();

double value = Double.parse(stringvalue);

but then I would need some way of writing

thename += value; // where something is done so the expression "thename" is actually the string corresponding to thename.

-Larry 


Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/3/2008 5:04:40 PM

ldechent:

If I understand correctly, when you mention wanting a more type safe solution, is that out of concern that someone might put text into a field entry that is supposed to have a numerical value, and vice versa?

Or is there some other concern?

Yes that is the main concern.  The other issue is that when you retrieve the values from the non-type-safe version, then you need to cast them to the appropriate types.  The only case that you might not, is when you aren't doing anything that requires the object to be a certain type, such as simply calling .ToString() on all the objects. 

I say when in doubt, use the type-safe solution, since it makes it much easier to deal with overall.  I think the non-type-safe APIs exist simply because .Net 1.1 didn't have Generics.

ldechent:

I should have wrote that the table already exists and it is in a database.

I thought that would be assumed but I was incorrect, as I see from the two replies.

I apologize for not being more specific in the original question.

 

I think I can complete this if I use a while (reader.Read()) to cycle through what was selected in the table in the database.

I think I can use

thename = reader["ingredient"].ToString();

string stringvalue = reader["weight"].ToString();

double value = Double.parse(stringvalue);

but then I would need some way of writing

 

I am not sure what the Reader API does as my company uses a Database wrapper class, but the idea is right. 

Assuming I read your first post right, you want to create a C# Data structure from the data in the database, right? If that's the case, then you can use the following code assuming that you can get a DataView from the reader (again, I don't know what the DataReader API looks like, so this will probably require some changes): 

List<Ingredient> recipe = new List<Ingredient>();
foreach (DataRow row in myReader.DataView.Tables[0].Rows)
{
    string name = row["ingredient"].ToString();
    double weight = double.Parse(row["ingredient"].ToString());
    recipe.Add(new Ingredient(name, weight));
}

If you need to display in the Web Page (as a table or whatever) you can use a DataGrid (If you need a simple table) and just databind it.

0
ADavis
1/8/2008 9:57:57 PM
Reply:

Similar Artilces:

compare single-valued-variable with multi-valued-variable
i�d like to compare a value with a list of values from a variable (see var2, where the notation is like regex) and set a local-var to 1 if match is found, else to 0. what i do not know how to compare one value regex-wise. i can make for each value a policy, but is there a more elegant way? <do-set-local-variable name="var2" scope="policy"> <arg-string> <token-text xml:space="preserve">154|155|157|175|330|530|719|745</token-text> </arg-string> </do-set-local-variable> this one should kind of loop through the...

making a variable name a variable value?
Hi there, I was wondering how to make a variable name the value of another variable. Do we do this using pointers? for example: $name = "jerry"; how can I establish a variable with the name $jerry ? thanks for the help, c. On 12 Jun 2001 09:15:37 -0700, Chirag Patel wrote: > Hi there, > > I was wondering how to make a variable name the value of another variable. > Do we do this using pointers? > > for example: > $name = "jerry"; > > how can I establish a variable with the name > $jerry ? > > thank...

If Not value or value then....
Hi all,I want to write a simple IF Not then statement in ASP.net 2.0 and I would like some help please.  If Not ntuser = "DOMAIN\ntuser" Or ntuser = "DOMAIN\ntuser2" Then Panel1.Visible = False End If Doesnt work, can you tell me where i'm going wrong please?many thanks.  The first place you're going wrong is in telling us it "doesn't work" without providing any details. JeffPlease: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue. Use Not as stated below. It ...

how to get variable value by using variable name as parameter???
I have a problem as following; I want to give my variable name as parameter to a function, then get value of that variable. Like this; dim myValue, myVariable, result  as stringmyValue = "demo"myVariable = "myValue"result = SomeMagicFunction(myVariable)then value of result sould be demoI know that is an interesting case. But i need this. :( Please help me !!... If you explain the situation where it is going to be used, there may be some other alternative solution to it. One solution is to store value in a property of a class or structure and then later on use reflection to retrie...

how to access/assign values to variables of aspx code-behind page in javascript code?
Hi, Can anyone help me with this? How to access or assign values to variables of aspx.cs code behind page using javascript code in the aspx page. Will be eagerly waiting for a reply. Thankyou. Raj. here is one way..assign hidden fields to any values you want to get at Page.RegisterHiddenField("fieldName", "fieldValue") then I think in Javascript it would be something like document.forms[0].fieldName.value; to get at it. Ask and it will be given to you; seek and you will find; knock and the door will be opened to you. Luke 11:9 hi Michael, ...

Adding variables whose name is another variable's value
I am trying to add a new controls within a loop. This requires me to create new variables within a loop, but how do I name a variable with a another variable's name. Here is my code (DR1 is a Data.SqlClient.SqlDataReader). 1             Dim Image As New Image2                    If IsDBNull(DR1) = False Then3                     &...

Extract values from SQL Results and Pass value to variable
What is the syntax to get the value from a sql command and pass it to a variable? This is what I have...VB.NET This stored procedure returns a number.... cmdSelectEmp = New SQLCommand ("NIO_Get_EMP_ID",Conn) cmdSelectEmp.Commandtype = CommandType.StoredProcedure cmdSelectemp.Parameters.Add("@User",cUser) How can I pass that number to my variable? myVar=We must become the change that we want to see! Add a parameter with .Direction = to ParameterDirection.ReturnValue and check that value: cmdSelectemp.Parameters.Add("returnValue").Di...

How to hold the values in session variable from intersoftWebcombo after we select the values from it
Hi,  I have a intersoft webcombo in .aspx page and when i select a value from it and go to another .aspx page the same selected value should appear in the webcombo in  second .aspx page For this i wrote an event webcombo_OnAfterItemSelected() event in .js file  webcombo_OnAfterItemSelected() { var WebCombo = ISGetObject(controlId); session["webcombovalue"]=WebCombo .Text; } But the value is not holding in session variable at client side. How to handle this situation???     Hi Neerja, You can't store the value in .js file, you should ...

How can I get a "variable value" from the "variable name"
Hi All, How can I get a "variable value" from the "variable name" ? For Example: ClassDefinition cd_def VariableDefinition vd_def cd_def = this.classdefinition For li_i = 1 To UpperBound (cd_def.VariableList) vd_def = cd_def.VariableList[li_i] MessageBox ("Variable Name: ", vd_def.name ) MessageBox ("Variable Value: ", "??????????") Next Thanks, Gustavo Which value do you expect to get? pbm_thisusuallydoesnothelp:-)) Philip Salgannik <Gustavo> wrote in message news:4069b28a.30f0.846930886@sybase.co...

Setting a local variable to a DB value in the code behind?
this is C#  I simply want to set a local variable to the value of something stored in my database but I can't seem to find ANYTHING like what I need I looked at using datasource.selectparameters but don't think it does what I need it to do  i basically need Dsource.SelectCommand = "SELECT (UserName, IntVal1, IntVal2 FROM Users)"; int k = IntVal2; I feel bad asking basic questions like this but I've been trying to figure out how to do this for an hour and a half, the help on the web is so amorphous because everything is so flexible in asp.ne...

Write the value of a derived variable in a SelectCommand in web form
Hello,I am trying to build a web application where I do a search into database. I have a code which separates the search words and creates a search command.  This works fine and I can print the search command into the screen with the TextLabel.Text property, the output is for example like this:(Institute LIKE N'%reindeer%)' OR (Institute LIKE N'%research%') OR (Keywords LIKE N'%reindeer%)' OR (Keywords LIKE N'%research%')I just can't figure out how I can put this variable into the SelectCommand in GridView, after the WHERE command, see below:SelectCommand="SELECT ID, Institute, Place,...

How to get html hidden variable value in code behind?
1.Put html hidden box in apsx page: <input type="hidden" id="hiddenVar" name="hiddenVar" runat="Server"/>2.Then add a js for for textbox keydown event in Page_Load event:txtMyBox.Attributes.Add("onkeydown", "document.getElementById('hiddenVar').value = 1);")3. Then I want to get the value for this hidden box in other event code-behind:  Dim hiddenValue As String = Request("hiddenVar")  but I get nothing,  how to get this hidden box value in code behind?   KentZhou:Dim hiddenValue As Str...

Why replacing fixed values with variables values the procedure become slow ????
Hi all, I'm completing the porting tests of ours applications from MSSqlServer to ASA (Version 9.0.0.1108) and i would like submit you a strange behavior .... I have attached a full (and small) batch-script that build the table and the 3 storeds procedures used for the tests. The test wants insert 100.000 records in this table (named "T1") and display a simple benchmark. To do this, i use a main stored procedures ("T1_monitor") that cyclically launch another stored procedure and display the required execution time every 1000 cycles. I've also added a num...

value of variable switches from ' ' to 'value'
--------------000108090907030800060105 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit I'm trying to figure out what exactly a script I wrote (see the attachment) is doing by stepping through it in the debugger. I have an array of dates in %Y-%m-%d format for each of the last 7 days. So, for instance, the range of dates for today (June 17, 2007) is from the 10th to the 16th. I then take these dates and use them to find work tickets in our ticketing system which were last updated on the day currently being checked. So, the first date would be 200...

get html textbox value in C#.net(code behind)
  i am new to ASP.net. Can anybody say how to get Input textbox value in C#.net. b4 sending answer Thankx  string value = Resquest.Form["textboxname"].ToString(); Hi,There are two ways to access it. 1) Make it runat="server" and access it in code behind like textbox1.value2) Another way is by using     Request.Form["textbox1"].ToString(); I hope this will be helpful to you.Thanks, Alpesh DhaneshaPlease don't forget to "Mask as Answer" if it helped. just add runat =server to html  ...

Web resources about - Field1 value --> variable name ; Field2 value --> variable value (C# code behind) - asp.net.web-forms

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Staley: 'A lot of different variables...been a hard year'
... 41° Navigation Home Giants A's Sharks Warriors Kings 49ers Raiders Quakes Insiders More Tickets Shop Watch Staley: 'A lot of different variables...been ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

Resources last updated: 1/8/2016 7:28:38 AM