I have a class named Result
which has 4 fields as id, marks, total, avg
. I created the List class and stored the result.
Now I want to display only 2 columns in the datagrid. They are id
and total
. I successfully displayed the id and total but the datagrid shows 4 columns instead of 2. The columns are id, total, id, total
Here is my code to display the datagrid:
private void Form1_Load(object sender, EventArgs e)
{
List<Result> result = new List<Result>();
PopulateResult();
dgresult.AutoGenerateColumns = false;
dgresult.Items.Clear();
dgresult.ItemsSource = result;
DataGridTextColumn col1 = new DataGridTextColumn();
col1.Header = "Id";
col1.Binding = new Binding("Id");
DataGridTextColumn col2 = new DataGridTextColumn();
col2.Header = "Total";
col2.Binding = new Binding("Total");
dgresult.Columns.Add(col1);
dgresult.Columns.Add(col2);
}
}
class Result
{
int id;
int total;
int marks;
int avg;
public int Id { get { return id; } set { id = value; } }
public int Total { get { return total; } set { total = value; } }
public int Marks { get { return marks; } set { marks = value; } }
public int Avg { get { return avg; } set { avg = value; } }
public Result(int ID, int TOTAL, int MARKS, int AVG)
{
id = ID;
total = TOTAL;
marks = MARKS;
avg = AVG;
}
}
I don't understand why it is happening like this.
Thanks in advance.
I've added comments to your code that show my thoughts:
private void Form1_Load(object sender, EventArgs e)
{
// Make a new list of result class objects, local to the Form1_Load method:
List<Result> result = new List<Result>();
// Call a method that populates a list... wait, what list?
PopulateResult();
dgresult.AutoGenerateColumns = false;
dgresult.Items.Clear();
// Set the datagrid data source to the list created earlier
dgresult.ItemsSource = result;
// ...
I'm not sure why the datagrid has a duplicate set of columns after you've specified and added only two columns. It would help to see the method PopulateResult()
.
The list that PopulateResult()
is adding to must be some other list, because the one created in Form1_Load
is local in scope.
I'm not sure if this is just a little oversight, or if you need to learn about variable scope. Forgive me if this is already known to you:
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.