2

Hey guys. I am using a ListView with two columns to read a table off a SQL server. So everything was right, when I had it a ListBox, but now that I changed to ListView and made columns something has gone wrong and the rows are coming in but there is no text, so it is just showing me a blank ListView that is scrollable.

Here is the XAML for the ListView:

<ListView Height="315" HorizontalAlignment="Left" Margin="26,15,0,0" Name="listView1" VerticalAlignment="Top" Width="324">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Title}" Header="Title" Width="240"/>
            <GridViewColumn DisplayMemberBinding="{Binding Price}" Header="Price" Width="75"/>
        </GridView>
    </ListView.View>
</ListView>

And this is the code being called on the TextChanged event to call it in from server table.

public void addtoList()
{
    cn.Open();
    String cmdString = "Select Title, Price from tblCart";
    SqlCommand cmd = new SqlCommand(cmdString, cn);
    SqlDataReader dr = cmd.ExecuteReader();
    double subT = 0;
    double tax = 1.09;
    double total = 0;

    while (dr.Read())
    {
        int count = dr.FieldCount - 1;

        for (int i = 0; i < count; i++)
        {                 
            listView1.Items.Add(dr["Title"].ToString());
            listView1.Items.Add(dr["Price"].ToString());
            subT += Convert.ToDouble(dr["Price"]);                    
        }                
    }

    total = Convert.ToDouble(subT * tax);
    subTotal.Text = subT.ToString();
    totalBlk.Text = total.ToString();
    cn.Close();
}

Any information on how to fix this will be greatly appreciated!

1
  • You are adding a row for each column. ListViewItem does not have custom properties. You will need to create a class or stuct to hold your properties Title and Price. Commented Apr 29, 2013 at 20:26

2 Answers 2

1

There should be a custom object like following code,

public class CustomItem
{
    public string Title { get; set; }
    public string Price{ get; set; }
}

and then add the custom item to the list

listView1.Items.Add(new CustomItem{Title =dr["Title"].ToString(), Price=dr["Price"].ToString()});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for accepting. and hope you will vote the answer when you are eligible to vote :)
0

You are adding items to the listview collection. Bind the listview's items source to the data table of the result:

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);


listView1.ItemsSource = ds.Tables[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.