简体   繁体   中英

How to get value from datalist in c#?

I am trying to retrieve a value from a DataList to use it in some formula

so I tried this code and I included it in the OnClick button event:

float fQ = float.Parse(Qtytb.Text);
float ftotal;
float fitem = float.Parse(pricelst.SelectedItem.ToString());
ftotal = fQ * fitem;
totaltb.Text = ftotal.ToString();

But it gave me null pointer exception at this point

( float fitem = float.Parse(pricelst.SelectedItem.ToString()); )

How can I get that to work?

add below validation

if(pricelst.SelectedItem != null)
{
  //your code....

}

You need to check if either pricelst , or pricelst.SelectedItem is null and handle these cases appropriately. For example, you could use float.TryParse(...) or the null coalescing operator ?? .

As an example:

Given the class

   private class Foo
   {
       public string SelectedItem { get; set; }
   } 

check for null like this:

Foo pricelst = new Foo();

    float fitem;

    if(float.TryParse(pricelst.SelectedItem, out fitem))
    {
        // set defaults here
        fitem = 0;
    }

try

var selectedItemValue =  pricelst.SelectedItem == null ? "0" : pricelst.SelectedItem.ToString();
var selectedItemFloat = float.Parse(selectedItemValue);
var fQ = float.Parse(Qtytb.Text);
var ftotal = fQ * selectedItemFloat;
totaltb.Text = ftotal.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM