简体   繁体   中英

Binding Dynamic list to a GridView

What is the best way to bind a dynamic list to a GridView (devexpress) in C#. By saying dynamic list I mean that each time user selects some value from GUI a select query is executed on database on different tables. The table varies for each user selected value and hence no. and types of returning columns are not fixed.

I did a little bit of search and found that dictionary is a good option but is there any better solution ? Could anyone please also give some rough steps on how to bind a dictionary fetching data from db to gridview (exact code is not required).

Please also not that my preference is to reduce the code as much as possible.

Thanks!

So I finally found the solution and thought to share here in case someone might need it. This is what I did:

  1. Created a class containing two properties Column and Value lets call this class Item

  2. Created another class ItemList which implments bindinglist of above class (Item)

    class ItemList : System.ComponentModel.BindingList< Item >

  3. class ItemList has two variables _tableName and _primaryKey

  4. User excutes the GetList(string TableName) function of ItemList class and passes tablename.

  5. GetList executes SQL query with table Name being passed as Parameter to this function

     ct.Append(" SELECT * "); ct.AppendLine(" FROM "); ct.AppendLine(TableName); 

    .....

  6. Read the result in Items as:

      if (dataReader.Read()) { for (int i = 0; i < dataReader.FieldCount;i++ ) { dataReader.GetName(i); dataReader.GetValue(i); this.Add(TreeItemInfo.GetItem(Convert.ToString(dataReader.GetName(i)), 

    Convert.ToString(dataReader.GetValue(i)))); } }

  7. GetItem in Item class:

      internal static Item GetItem(string column, string value) { Item item = new Item(); item._column = column; item._value = value; return item; } 

This way I was able to retrieve a list of object of class Item containing columns names and their values. This solution would work with any table and no. and types of columns are not pre defined.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM