none
how to bind an array of string with DataGridView ? RRS feed

  • Question

  • Hi,

     

    Can I bind an array of string with DataGridView ? Can some one point me to a sample code or a good tutorial about binding DataGridView to an array of string or integer.


    Regards,

     

    Pranav

     

    Monday, November 19, 2007 4:59 PM

Answers

  • If you set the dataGridView1.datasource = yourStringArray, you're probably finding that the datagrid displays the length of each string instead of the string. It's because if the dataGridView1.DataMember defaults to the first public property of the type it is bound to which in the case of System.String, is the Length. I think what you'd have to do is wrap the string class to proivde a public property exposing the string value to the datagrid. Then instead of an array of strings (or integers) have an array of your wrapper class objects. I know that probably doesn't give you the answer you wanted but I haven't found another way. Here's a link to some examples:

     

    http://www.devx.com/dotnet/Article/33748

    Monday, November 19, 2007 7:31 PM

All replies

  • If you set the dataGridView1.datasource = yourStringArray, you're probably finding that the datagrid displays the length of each string instead of the string. It's because if the dataGridView1.DataMember defaults to the first public property of the type it is bound to which in the case of System.String, is the Length. I think what you'd have to do is wrap the string class to proivde a public property exposing the string value to the datagrid. Then instead of an array of strings (or integers) have an array of your wrapper class objects. I know that probably doesn't give you the answer you wanted but I haven't found another way. Here's a link to some examples:

     

    http://www.devx.com/dotnet/Article/33748

    Monday, November 19, 2007 7:31 PM
  • Never tried to do it....but can't you bind a bindingSource to an object.  Including objects within your program....like a class....like an array....like an enumeration....?

    Monday, November 19, 2007 7:49 PM
  • Yes, if you're using the designer you can select an object datasource and find the class you want to bind to. In code (C#) you can just say bindingSource1.DataSource = typeof(YourClass). bindingSource1 is your binding source and YourClass is the class you're binding to. It will then be able to bind to the public properties.

     

    The problem is a string has no public property for its actual value.

    Monday, November 19, 2007 7:56 PM
  • This seems to be a problem. Having to create a wrapper class for something as simple as a string seems to fly in the face of what binding was intended to provide to developers. My two cents anyway.

     

    Surely there is a way to do this.

    Tuesday, December 4, 2007 10:06 PM
  • Please let us know if you find one.

    Tuesday, December 4, 2007 10:20 PM
  • I think I have a pretty good workaround using LINQ and anonymous types:

     

    Code Block

    List<string> names = new List<string>(new string[]

    {

    "John",

    "Frank",

    "Bob"

    });

     

    var bindableNames =

    from name in names

    select new {Names=name};

     

    dataGridView1.DataSource = bindableNames.ToList();

     

     

    This will bind the actual string values to the DGV in a column called "Names", which you can change to whatever you want in the anonymous type initializer.

     

    This isn't perfect, but it does avoid having to define a fake class, and you can easily name the column or columns whatever you like.

    Tuesday, December 4, 2007 10:47 PM
  •  xr280xr wrote:

    Yes, if you're using the designer you can select an object datasource and find the class you want to bind to. In code (C#) you can just say bindingSource1.DataSource = typeof(YourClass). bindingSource1 is your binding source and YourClass is the class you're binding to. It will then be able to bind to the public properties.

     

    The problem is a string has no public property for its actual value.

     

    That is because strings are not value types like other types; i.e. int, decimal.  They are actually reference types.  They contain a reference to the string, not the actual string itself.  The other default types consume a known amount of memory.  Strings are dynamic, and memory consumption can vary.  A reference is what is actually stored.

    Tuesday, December 4, 2007 11:21 PM
  •  

    You could try this:

     

    Code Block

    DataGridView1.Rows.Add(new Object[] {1, "Jones"});

     

     

    Of course you can add as many strings or integers as you like.

     

     

    Wednesday, December 5, 2007 1:14 AM
  •  

    Hi there,

     

    I have answered this question in another post. Basically, you cannot bind an arry to a DataSource. It is impossible to do it directly... Cause an array is a type. AFAIK

     

    To do this, there are many libraries that have an automated step to bind an array to a DataSource, all they do is iterate the array and add a new row to the data source..

     

    For instance, say we are creating a two dimensional array, and we want to bind it, similar goes for n-dimension (but it isn't good to bind a huge array as a DataSource (after conversion) since the complexity will increase cause it is a for loop for each dimension.

     

    Code Block

    int NumColumns = 3;

    int NumRows = 3;

     

    Random rnd = new Random();

     

    // Lets add columns, we can't add rows without columns

    for (int i = 0; i < NumColumns; i++)

    {

        string column = string.Format("Column{0}",i+1);

        dataGridView1.Columns.Add(column, column);

    }

     

    // Your data ...

    for (int row = 0; row < NumRows; row++)

    {

        // We need to save each row as an array

        string[] currentColumn = new string[NumColumns];

     

        // We we add each column to the currentColumn

        for (int col = 0; col < NumColumns; col++)

            currentColumn[col] = rnd.Next(0, 100).ToString();

     

        // We add that to the gridView

        dataGridView1.Rows.Add(currentColumn);

    }

     

     

    It is pretty straight forward, I am adding a column of strings. As the previous poster mentioned, that array could be an object instead and you could have strings, ints, textboxes etc for each one Smile

     

    If you have more questions, let us know.

    Wednesday, December 5, 2007 5:40 AM
  • Well, you can a) create a class just to hold your data, b) add columns and rows  to the DGV, or c) you can just use an anonymous type, as I listed previously.

     

    This seems very straightforward, and it is a quick solution to allow you to bind a list of strings or whatever. It basically just gives you a shortcut to create the class that is bound to the DGV. Try it out. I think you'll like the results and you'll only have like 2 or 3 extra lines of code (the LINQ statment).

     

    Wednesday, December 5, 2007 3:26 PM
  • A good solution as long as you're using .NET 3.0...but most people aren't yet.

    Wednesday, December 5, 2007 4:11 PM
  • True. But at least you have something to look forward to Smile

     

    Also, it is in .Net 3.5 (c# 3.0), just for reference.

     

    Tuesday, December 11, 2007 10:26 PM
  • If this is for a Winform App i've manage to do the bind like this:


    First i have a Class with a construtor for this 'List of contacts)

    The class as 4 string variables (the come from an LDAP querry) but this doesn't matter what you need is to make a class that save the current state of the strings and add then to the array (LIST)

    Code Snippet
    List.Add(new ListAD(nome, mail, telef, mobile));

     

     




    Then set the grid datasource to to Array like this:

    Code Snippet
    dgvFCL.DataSource = List;

     

     



    It will populate the grid with all the columns(strings in the class) / rows (values of the array)

    Ofc you have to do this in a For/Foreach


    My complete code is this for you to get this easier:

    Code Snippet
    foreach (SearchResult searchResults in rootSearcher.FindAll())
    {

    string nome = "";
    string mail = "";
    string telef = "";
    string mobile = "";

    foreach (string propertyName in searchResults.Properties.PropertyNames)
    {
    foreach (Object retEntry in searchResults.Properties[propertyName])
    {
    {
    switch (propertyName)
    {
    case "displayname":
    nome = retEntry.ToString();
    break;
    case "mail":
    mail = retEntry.ToString();
    break;
    case "telephonenumber":
    telef = retEntry.ToString();
    break;
    case "mobile":
    mobile = retEntry.ToString();
    break;
    }
    }
    }
    }

    List.Add(new ListAD(nome, mail,
    telef, mobile));
    }

    dgvFCL.DataSource = List;

     

     


    If u need help with the constructor (ListAD class) just ask

    Wednesday, April 16, 2008 10:05 AM
  • I forgot.. at the top i allways clear the ArrayList (List.Clear())

     

    Wednesday, April 16, 2008 10:20 AM
  •  vtcoder wrote:

    I think I have a pretty good workaround using LINQ and anonymous types:

     

    Code Block

    List<string> names = new List<string>(new string[]

    {

    "John",

    "Frank",

    "Bob"

    });

     

    var bindableNames =

    from name in names

    select new {Names=name};

     

    dataGridView1.DataSource = bindableNames.ToList();

     

     

    This will bind the actual string values to the DGV in a column called "Names", which you can change to whatever you want in the anonymous type initializer.

     

    This isn't perfect, but it does avoid having to define a fake class, and you can easily name the column or columns whatever you like.



    THIS IS AWESOME!!! Thanks pal!!!!
    Sunday, November 30, 2008 11:07 AM
  • Hy,

    Don't know if this works in your programming language, but in VB 2005 it's possible to pass an one-dimensional array to the datagridview.rows.add method. So the solution in my language (after poking around quite a while) was:

    datagridview.rows.add (array)

    Greetings from Holland,


    Alfred Zwiep

    Tuesday, January 20, 2009 8:42 PM
  • Hi, sometime I got the same problem like you and I found a simple way to do it, i think it will be helpfull here. Following is the sample code with a Datalist control and Gridview control is the same:

    //Declare an array of string and bindding to Datalist as normal way:

    string[] s = new string[] { "Microsoft", "Sun System", "IBM" };

    this.DataList1.DataSource = s;

    this.DataList1.DataBind();

    //And the code for the Datalist in the design:

    <asp:DataList ID="DataList1" runat="server">

    <ItemTemplate>

    <asp:Label ID="Label1" runat="server" Text="<%# GetDataItem().ToString() %>"></asp:Label>

    </ItemTemplate>

    </asp:DataList>

    Insteed of using Eval(), I called GetDataItem(), which exactly is public method Page.GetDataItem() and it return the currently bidding DataItem of the control. You will see that after '<%#', you can call every public method you want and it will help you in other problems.

    Buck Nguyen

    • Proposed as answer by Buck Nguyen Monday, March 16, 2009 4:11 AM
    Monday, March 16, 2009 3:41 AM
  • Hi Pranav,

    Try this:

    IList<string> list_string = new List<string>();
    list_string.Add("Microsoft");
    list_string.Add("IBM");
    list_string.Add("SunSystem");
    DataGridView.DataSource = list_string.Select(x => new { Value = x }).ToList();
    DataGridView.Show();

     

    Hope this helps

    Thanks

    Monday, July 12, 2010 5:01 AM
  • try

    string[] columnNames = ds.Tables[0].Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
                    List<string> names = new List<string>(columnNames);
                    var bindableNames =
                            from name in names
                            select new { Names = name };
                    grdCustomerField.DataSource = bindableNames.ToList();

    Wednesday, May 30, 2012 10:50 AM
  • Here's what I do:

    Code Behind:
    GridView1.DataSource = New String(){"Hello","World"}
    GridView1.DataBind

    HTML

    <asp:GridView ID="GridView1" runat="Server">
    <Columns>
    <asp:TemplateField HeaderText="Message">
    <ItemTemplate>
    <%#Container.DataItem%>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>

    • Proposed as answer by Wayne Allen Thursday, January 31, 2013 10:56 PM
    Friday, September 21, 2012 6:07 PM