How to display items in listbox using c# [Resolved]

Posted by Kundan under C# on 8/29/2013 | Points: 10 | Views : 5799 | Status : [Member] | Replies : 2
How to display items in listbox using c#




Responses

Posted by: Jayakumars on: 8/30/2013 [Member] [MVP] Bronze | Points: 25

Up
0
Down
hi

try this pure asp.net C# Code

SqlConnection con = new SqlConnection("data source =Test;initial catalog =Test; user id=sa;pwd =test;");
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
string str;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
listboxbind();
}
}

private void listboxbind()
{
con.Open();
str = "select * from employee";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "employee");
dt = ds.Tables["employee"];
ListBox1.DataTextField = "Department";
ListBox1.DataValueField = "EMPLOYEEID";
ListBox1.DataSource = ds.Tables["employee"];
ListBox1.DataBind();
con.Close();

}

Mark as Answer if its helpful to you

Kumaraspcode2009@gmail.com

Kundan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vedikaledange on: 1/2/2019 [Member] Starter | Points: 25

Up
0
Down
You may use this code to add icon to listBox

/ GListBoxItem class
public class GlistBoxItem
{
private string _myText;
private int _myImageIndex;
// properties
public string Text
{
get {return _myText;}
set {_myText = value;}
}
public int ImageIndex
{
get {return _myImageIndex;}
set {_myImageIndex = value;}
}
//constructor
public GListBoxItem(string text, int index)
{
_myText = text;
_myImageIndex = index;
}
public GListBoxItem(string text): this(text,-1){}
public GListBoxItem(): this(""){}
public override string ToString()
{
return _myText;
}
}//End of GListBoxItem class
// GListBox class
public class GListBox : ListBox
{
private ImageList _myImageList;
public ImageList ImageList
{
get {return _myImageList;}
set {_myImageList = value;}
}
public GlistBox()
{
// Set owner draw mode
this.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
GListBoxItem item;
Rectangle bounds = e.Bounds;
Size imageSize = _myImageList.ImageSize;
try
{
item = (GListBoxItem) Items[e.Index];
if (item.ImageIndex != -1)
{
imageList.Draw(e.Graphics, bounds.Left,bounds.Top,item.ImageIndex);
e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor),
bounds.Left+imageSize.Width, bounds.Top);
}
else
{
e.Graphics.DrawString(item.Text, e.Font,new SolidBrush(e.ForeColor),
bounds.Left, bounds.Top);
}
}
catch
{
if (e.Index != -1)
{
e.Graphics.DrawString(Items[e.Index].ToString(),e.Font,
new SolidBrush(e.ForeColor) ,bounds.Left, bounds.Top);
}
else
{
e.Graphics.DrawString(Text,e.Font,new SolidBrush(e.ForeColor),
bounds.Left, bounds.Top);
}
}
base.OnDrawItem(e);
}
}//End of GListBox class


DOT NET

Kundan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response