简体   繁体   中英

Passing parameter to a function in C#

I have a small program. It includes a listbox and few textboxes. There are few elements in the listbox and depending on the selected index it outputs the corresponding values into the textboxes.

Code example: http://notepad.cc/share/AGh5zLNjfJ

I want to use a function to print the values into the textboxes instead of typing them over and over again in switch cases.

Something like this:

switch(personList.SelectedIndex)
{
    case 0:
        output(person1);
        break;
    case 1;
        output(person2);
        break;
}

I couldn't pass the person object and access its properties with the function I created. SOS.

Instead of switching by selected index, assign list of persons as data source to listbox. When selected index changes - show data of selected item in textboxes:

// that's just creating list of People with NBuilder
var people = Builder<Person>.CreateListOfSize(5).Build().ToList();
personList.DisplayMember = "fname"; // set name of property to be displayed
personList.DataSource = people;

Then on selecting person from list:

private void personList_SelectedIndexChanged(object sender, EventArgs e)
{
    Person person = (Person)personList.SelectedItem;
    output(person);
}

Keep in mind that in C# we use PascalNaming for methods and properties.

Is your output function similar to this ??

public void output(Person p)
{
    idBox.Text = p.id;
    nameBox.Text = p.name;
    lNameBox.Text = p.lName;
}

You can get selected Item as following (if you have bounded the listbox with list of person as datasource)

Person p = (Person)listBox1.SelectedItem;

From your code i guess you need a function. you can do it like this

private void Output(Person p)
{
     idBox.Text = p.id;
     fnameBox.Text = p.name;
     lNameBox.Text = p.lName;
}

and call it like you are calling.

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