Mohammad Hani Mohammad Hani - 2 months ago 9
C# Question

Value's Not Appearing In Datagrid?

What I'm trying to do?

I'm working on project i.e. Online Stock/Shares Marketing. In which client will able to set some order and can see details on his/her screen. For this I'm using WPF + C# and using datagrid so all products, rates and all of its detail will be listed in that grid in a tabular form. And data will be fetched from Sql Server Management Studio. Moreover, I'm binding data in datagrid.

What Problem I'm Facing?

Problem I'm facing is that in datagrid rows are added but data is not appearing in those rows. For example if there is 4 rows in database, same no. of rows is appearing on datagrid but empty rows are appearing :(.


XAML:-

<DataGrid IsReadOnly="True" x:Name="pa" AutoGenerateColumns="False" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding ProductName}" Width="2*" />
<DataGridTextColumn Header="Price" Binding="{Binding ProductPrice}" Width="2*" />
<DataGridTextColumn Header="Unit" Binding="{Binding ProductUnit}" Width="2*" />
<DataGridTextColumn Header="Stock" Binding="{Binding ProductStock}" Width="2*" />
<DataGridTextColumn Header="Code" Binding="{Binding ProductCode}" Width="2*" />
</DataGrid.Columns>
</DataGrid>


C#:-

static ObservableCollection<ProductAva> collection = new ObservableCollection<ProductAva>();
private string ProductName { get; set; }
private string ProductPrice { get; set; }
private string ProductUnit { get; set; }
private string ProductStock { get; set; }

private string ProductCode { get; set; }


private void UserControl_Loaded(object sender, RoutedEventArgs e)
{




SqlConnection con = new SqlConnection("Server=DESKTOP-KE9BBUE;Database=Vegomart;Trusted_Connection=True");
con.Open();
SqlCommand command = new SqlCommand("select * from AddNewItem", con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
collection.Add(new ProductAva() { ProductName = reader.GetString(1), ProductPrice= Convert.ToString(reader.GetInt32(2)), ProductUnit = reader.GetString(4), ProductStock = Convert.ToString(reader.GetInt32(5)), ProductCode = reader.GetString(3)});
}

pa.ItemsSource = collection;

}


Please help me out..!!

Answer

Ahhh, At last I found solution to it.

instead of declaring properties private they should be public:-

  private string ProductName { get; set; }
private string ProductPrice { get; set; }
private string ProductUnit { get; set; }
private string ProductStock { get; set; }

Correction:-

  public string ProductName { get; set; }
public string ProductPrice { get; set; }
public string ProductUnit { get; set; }
public string ProductStock { get; set; }