1

I have a data bound listbox that lists names of items, I am now wanting to display both the item number and the Item name in something that looks like: i-001 - Item 1. I have done something similar to this, but it was when I was not using data text fields, but iDataReaders instead.

so can I append the datatextfield attribute in anyway to accept more than one column? Either in the aspx page or in the code behind?

If there is any code that can be of help I can provide it to you, if there is any clearing up that can be done I will do my best to do so.

Thank you

Sample Code:

listItems.DataSource = DAL.Util.getItemProfiles(vendor,catalog);
listItems.DataBind();


public string ItemNumName
{
    get { return "CustItemNum" + " - " + "Name"; }
}

protected void listItems_DataBound(object sender, EventArgs e)
{
    listItems.DataTextField = ItemNumName;
}

this cause the following error message:

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'CustItemNum - Name'.

If I remove the + " - " + "Name" from the property it functions correctly by showing just the CustItemNum field

Joe W
  • 1,567
  • 6
  • 23
  • 36

3 Answers3

1

You can add a new property to your model that combines the two fields and use it as datavalue

  public string SomeProperty
  {
      get{return  itemnumber + "-"+ itemName ; }
  }
anouar.bagari
  • 2,084
  • 19
  • 30
  • I am attempting to use this method but am having problems, I set the listboxs DataTextField = ItemNumName it looks for a column named : 'CustItemNum - Name' .. And sorry for a long wait for reply I was away from this for a while.. I am sure with a little more tweaking with this method I will be able to get it to work. Thank you – Joe W Jun 15 '12 at 14:53
  • @JoeW What is the type of the datasource? – anouar.bagari Jun 15 '12 at 15:08
  • well I could have swore I posted this earlier... data type is varchar. – Joe W Jun 15 '12 at 19:45
1

You can do this in the OnDataBound event of the ListBox. Examples here: http://asp-net-example.blogspot.com/2011/07/how-to-use-listbox-ondatabound-event-in.html

 protected void ListBox1_DataBound(object sender, EventArgs e)  
    {  
//... your logic here to set the text of the item
}
  • Alright using this I am able to set the datatextfield to one column, but I am still having problems appending the 2nd column. Thanks for the response – Joe W Jun 05 '12 at 14:07
1

you could also edit your sql to concatenate the two columns and then use that as your datatextfield. Using provided variable names it would look something like:

Select CustItemNum, Name,  CustItemNum + ' - ' + Name AS NumberName

then you should be able to use NumberName as the DataTextField and it should display like "itemNumber - itemName"

John
  • 134
  • 1
  • 10