开发者

C#: Adding Columns To Bound DatagridView With Code

开发者 https://www.devze.com 2022-12-26 19:51 出处:网络
// Getting data from this Admin class: public static IQueryable<Student> GetStudents() { DojoDBDataContext conn = new DojoDBDataContext();

// Getting data from this Admin class:

public static IQueryable<Student> GetStudents()
{
    DojoDBDataContext conn = new DojoDBDataContext();

    var query =
        from s in conn.Students
        join b in conn.Belts on s.BeltID equals b.ID
        orderby s.LastName ascending
        select s;

    return query;
}

// And on my form:

BindingSource bs = new BindingSource();

    private void fillStudentGrid()
    {
        bs.DataSource = Admin.GetStudents();
        dgViewStudents.DataSource = bs;
        dgViewStudents.Columns.Remove("ID");
    }

Works perfectly fine, but rather than 开发者_JAVA技巧removing 20+ columns of data that I don't want, I'd rather just add the few that I do. Plus, getting to name the header titles is a bonus. But, the add method isn't working for me:

private void fillStudentGrid()
{
    bs.DataSource = Admin.GetStudents();

    dgViewStudents.AutoGenerateColumns = false;
    dgViewStudents.DataSource = bs;
    dgViewStudents.Columns.Add("ID", "ID Number");
}

I get the appropriate number of rows, and the column title is set correctly... but the rows are filled with blank data.


The reason you're seeing no data is that you haven't actually bound the column to anything. The number of needed rows is determined by the binding, and the grid knows that should there be any columns, it needs one row per data item, but with no columns it shows nothing. When you add the new column, it will appear in all of the rows, but it's not automatically bound to your data source. To do that, you need to set the DataPropertyName on the column before you add it to the collection:

bs.DataSource = Admin.GetStudents();
dgViewStudents.AutoGenerateColumns = false;
dgViewStudents.DataSource = bs;

DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "ID";
col.HeaderText = "ID Column";
col.Name = "foo";
dgViewStudents.Columns.Add(col);


Student class properties can also be redesigned like that. With browsable false option you don't need to remove gridview column.

    using System.ComponentModel;

    [Browsable(false)]
    [Description("Öğrenci kayıt numarası")]
    [DisplayName("Öğrenci Kayıt No")]
    public int StudentID { get; set; }


You can also add columns to your query even when they are not present.

eg: select employeeID, empname, 0 as salary from table_name

and bound this to your datagridview.

0

精彩评论

暂无评论...
验证码 换一张
取 消