Reputation: 47
I am creating a custom usercontrol with a DataGridView
and I am adding this usercontrol to my form. In the Form1_Load
event I am initialising the user control by invoking the constructor of the user control. Its a parameterized constructor which has a List
as argument and the list is being used as the DataSource
for the DataGridView
in the user control.
The problem is: the DataGridView
is not loaded with the data.
can any one figure it out.
the code in the form load event is,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace usercontrol
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Car> cars = new List<Car>();
cars.Add(new Car("Ford", "Mustang", "1967"));
cars.Add(new Car("Shelby AC", "Cobra", "1965"));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", "1965"));
ucSample uc = new ucSample(cars);
}
}
public class Car
{
private string company;
private string color;
private string year;
public Car(string com,string col,string yea)
{
this.Company = com;
this.Color = col;
this.Year = yea;
}
public string Company { get; set; }
public string Color { get; set; }
public string Year { get; set; }
}
}
The code in the user control is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace usercontrol
{
public partial class ucSample : UserControl
{
public ucSample()
{
InitializeComponent();
}
public ucSample(List<Car> listString)
{
InitializeComponent();
DataSource = listString;
}
public object DataSource
{
get { return dgvSample.DataSource; }
set { dgvSample.DataSource = value; }
}
}
}
Upvotes: 2
Views: 1834
Reputation: 1
datagridview is in user control. that's why your Datagrid not loading with the user control in the Form.
Go to the userControl.cs
paste below code in the constructor
"this.studentTableAdapter.Fill(this.universityDataSet.Student);"
In my case, the dataset is universityDataSet and the table is Student
Upvotes: 0
Reputation: 23732
Your problem is that you create a custom control in an extra class but never add the control to your form to be displayed
A simple line will solve your problem:
this.Controls.Add(uc);
Put it in the constructor. That will ensure that your custom control is added to the Form
for display
EDIT:
there is of course also a manual way: Here is an answer with screenshots How do I add my new User Control to the Toolbox or a new Winform?
Here is another one : add user control to a form
Upvotes: 3