简体   繁体   中英

Binding List of strings to a DataGridView gives strings properties

I found one similar question in StackOverflow, but it has no answers. I'm trying to bind a IList<string> to a DataGridView as its DataSource , but instead of it output the list of strings, like in a ListView , it outputs me the properties of the elements in the list, in this case, Length .

My code:

public void FindMatches()
{
    const string regex = @"\{([a-zA-Z_][a-zA-Z0-9_]*)\}";
    IList<string> names = (from Match match in Regex.Matches(ObterConteudoArquivo(), regex) select match.Value).ToList();
    _view.Lista = names;
}

Now that I have a list stored in List that contains all my matches, example given { "{CP}", "{DP}", "{EP"} } , I want to bind them to my DataGridView:

public IList<string> Lista
{
    set
    {
        ltvCampos.DataSource = value;
    }
}

This binds only the Length of each string. I also did:

public IList<string> Lista
{
    set
    {
        foreach (string name in value)
        {
            DataGridTextBox row = new DataGridTextBox();
            row.Text = name;
            ltvCampos.Rows.Add(row);
        }
    }
}

The lexer says:

Method with 'params' is invoked. Have you intended to call more specific method 'int Add(object)'?

Take a look at the answer on this link . I think it is going to help you. They are using a BindingList<> instead of an IList<>

You need to wrap your strings in a class, which exposes them as public properties with both a setter and a getter:

class aString { public string theString { get; set; } 
                public aString(string s) { theString = s; }  }

Now create a list of strings..

List<aString> theStrings = new List<aString>();

..and fill it with your Matches:

theStrings  = (from Match match in Regex.Matches(text, regex) 
               select new aString(match.Value)).ToList();

Now you can bind your list to the DGV:

ltvCampos.DataSource = theStrings;

For added functionality you may want to insert one or two more layers of binding by using a BindingList (which among others will raise change events):

var blist = new BindingList<aString>(theStrings);
ltvCampos.DataSource = theStrings;

or both a BindingList and a BindingSource , which will present you with a wider range of options and methods:

var blist = new BindingList<aString>(theStrings);
var source = new BindingSource(blist, null);
ltvCampos.DataSource = source ;

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