0

I am trying to fetch the selected value of the listbox. When I actually try LstGroup1.SelectedItem I get the value { BoothID = "4", BoothName = "HP" } and even if i try to get the value from LstGroup1.SelectedValue the output is same. Now I want to fetch BoothID i.e. the expected output is 4 but i am unable to get so.

My ListBox name is LstGroup1.

public List<object> BoothsInGroup1 { get; set; }
// Inside the Constructor 
BoothsInGroup1 = new List<object>();
//After Fetching the value add 
BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });

//Now here I get 
var Booth = (LstGroup1.SelectedItem);
//Output is { BoothID = "4", BoothName = "HP" }

// Expected Output 4

Suggest me how to do that.


EDIT

public partial class VotingPanel : Window
{
    public List<object> BoothsInGroup1 { get; set; }
    public VotingPanel()
    {
        InitializeComponent();
        DataContext = this;
        BoothsInGroup1 = new List<object>();

        //Connection is done
        SqlConnection con = new SqlConnection(ConnectionString);
        con.Open();

        FieldNameCmd.CommandText = "SELECT * FROM Booth b, BoothGroup bg where bg.GroupID=b.GroupID;";
        IDataReader da = FieldNameCmd.ExecuteReader();
        while (da.Read())
        {
            if (Group1Name.Text == da["GroupName"].ToString())
            { // Adds value to BoothsInGroup1
                BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
            }
        }
    }
    private void BtnVote_Click(object sender, RoutedEventArgs e) // on Click wanted to find the value of Selected list box
    {   
        if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
        {
            var Booth = (LstGroup1.SelectedItem);
            //Few things to do 
        }
    }
}

XAML

<ListBox Grid.Row="1"
         Name="LstGroup1"
         ItemsSource="{Binding BoothsInGroup1}"
         Margin="5,1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding BoothID}"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Bottom"
                           FontSize="15"
                           FontWeight="ExtraBold"
                           Margin="5,3"
                           Grid.Column="1" />
                <TextBlock Text="{Binding BoothName}"
                           Grid.Column="1"
                           VerticalAlignment="Center"
                           FontWeight="ExtraBold"
                           FontSize="30"
                           Margin="15" />

            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • 2
    This question makes no sense at all. Please try write a proper question if you would like a proper answer – JKennedy Sep 02 '14 at 09:58
  • @user1 - Does it make sense now – Mohit S Sep 02 '14 at 10:12
  • whats your result if u try : var myBooth = LstGroup1.SelectedItem as Booth; This should work, cause your list contains literally 'Object's, not 'Booth's – Kooki Sep 02 '14 at 10:29
  • @Kooki - it doesn't give error but the myBooth is null and thus the next line will give error. – Mohit S Sep 02 '14 at 10:31
  • -1 On this site, we like words to accompany the code in our questions. Please edit your question to *describe* your problem(s) and what your requirements are. I'll be glad to remove this down vote once you have done that. – Sheridan Sep 02 '14 at 10:31
  • @Sheridan - I think i have done what is expected – Mohit S Sep 02 '14 at 10:37
  • 2
    +1 For now, I will accept that change because you have made an effort to improve your question. However, your question still falls below the average question quality on this website. For future reference, perhaps you should read through the [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) page from the Stack Overflow Help Center... remember, better questions mean more up votes and that provides you with more privileges on the site. – Sheridan Sep 02 '14 at 10:43

6 Answers6

9

since you are using anonymous type to populate the listbox, so you have left with no option then an object type to cast the SelectedItem to. other approach may include Reflection to extract the field/property values.

but if you are using C# 4 or above you may leverage dynamic

    if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
    {
        //use dynamic as type to cast your anonymous object to
        dynamic Booth = LstGroup1.SelectedItem as dynamic;
        //Few things to do 

        //you may use the above variable as
        string BoothID = Booth.BoothID;
        string BoothName = Booth.BoothName:

    }

this may solve your current issue, but I would suggest to create a class for the same for many reasons.

pushpraj
  • 13,458
  • 3
  • 33
  • 50
2

I think, you should try one of the following : //EDIT : This solution only works, if Booth is a class/struct

var myBooth = LstGroup1.SelectedItem as Booth;
String id =myBooth.BoothID;
String name=myBooth.BoothName:

or use a generic list with a different type :

public List<Booth> BoothsInGroup1 { get; set; }
....
var myBooth = LstGroup1.SelectedItem;
String id =myBooth.BoothID;
Stringname=myBooth.BoothName:

And if Booth isn't a class yet, add a new class:

public class Booth
{
    public int BoothID { get; set; }
    public String BoothName { get; set; }
}

So u can use it in your generic list, an you can fill it after databasereading

BoothsInGroup1.Add(new Booth
   { 
     BoothID = Convert.ToInt32(da["BoothID"]),
     BoothName = da["BoothName"].ToString() 
   });
Kooki
  • 1,157
  • 9
  • 30
1

Have you tried :

var Booth = (LstGroup1.SelectedItem);
string ID=Booth.BoothID;
string Name=Booth.BoothName:
apomene
  • 14,282
  • 9
  • 46
  • 72
  • 'object' does not contain a definition for 'BoothID' and no extension method 'BoothID' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference? – Mohit S Sep 02 '14 at 10:03
1

You can always create a class called Booth to get the data in the Object Format. From My point of view Dynamic is not the right way of doing this. Once you have the Class Booth in the Solution you can run

Booth Booth1 = LstGroup1.SelectedItem as Booth;
string BoothID1 = Booth1.BoothID;
0
public List<object> BoothsInGroup1 { get; set; }

BoothsInGroup1 = new List<object>();

BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });


var Booth = (LstGroup1.SelectedItem);
var output = Booth.BoothID;
JKennedy
  • 18,150
  • 17
  • 114
  • 198
  • No @user1 this is not what i want it is fetching the index but I want the value – Mohit S Sep 02 '14 at 10:00
  • do you mean you want `var output = Booth.BoothId`? – JKennedy Sep 02 '14 at 10:01
  • Yes I want Booth.BoothID – Mohit S Sep 02 '14 at 10:01
  • Its giving error :( the same one which i copied in the another answer – Mohit S Sep 02 '14 at 10:04
  • you said "'object' does not contain a definition for 'BoothID' [...]". What is the result of LstGroup1.SelectedItem.GetType()? Are you sure that your selected item is typeof(Booth)? Maybe your SelectedItem is bound to Property BoothID or BoothName. – Kooki Sep 02 '14 at 10:11
  • @Kooki - I dont know but while debugging I got this `base = {Name = "Object" FullName = "System.Object"}` – Mohit S Sep 02 '14 at 10:25
  • @SandipArmalPatil - Can we please comment on the main question... So that I'll get notification as well. What Description are you looking for – Mohit S Sep 02 '14 at 10:26
  • I am talking about answer provided by @user1.. Whenever your are posting answer there should be description along with code.. so it's easy to understand problem/solution.. – Sandip Armal Patil Sep 02 '14 at 10:29
  • @MohitShrivastava it also applicable for you because there is nothing in your question, What you want? what you have tried? what problem you are getting? you just post the code. – Sandip Armal Patil Sep 02 '14 at 10:32
  • @SandipArmalPatil - I think i have changed what is expected. If more do let me know. Thanks for your valuable comment. I didnt realize that it is not understanable – Mohit S Sep 02 '14 at 10:40
0

For those that know the type or object that they want the code will look like this:

private void lboxAccountList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      //Class object = (Class)listName.SelectedItem;
      // object.getName or object.getSomeVariable or object.callMethod(object.getName)

      Account account  = (Account)lboxAccountList.SelectedItem;
      MessageBox.Show(""+account.AccountNo+" "+account.Balance);          
}

Michal Kania
  • 609
  • 11
  • 24