Link to home
Start Free TrialLog in
Avatar of sivakugan
sivakugan

asked on

How to retrieve foreign key values in Drop Down list

Hi,

I have two tables as following.

CarCategory- CategoryID,Category-Name
Car - CarID,Descriptions,Seats,Photo,CategoryID(F.K)

I am using FormView to enter the details of Car.
So when the end-user enter values in car, The user should be able to enter Descriptions,Seats,Photo,instead of entering the category id , The end user should be able to select the Category Name from the drop down list .
( The CarID is the primary key, so the end user does not need to enter the values. it will automatically increase by 1.)

I am using object-datasource and sqldatasource in my applications.
My main goal is , when user enter the values for car tables, everything will be entered.
except the category ID, I want the user to select the Category-Name from the drop down list and Category-ID should be entered automatically into the Car Table, when user select the Category-Name.

Thanks
Avatar of kaminda
kaminda
Flag of Sri Lanka image

You can have add a datatable in to your dataset and get all the CategoryID,Category-Name
coulumns from CarCategory table to that datatable.  Then bind that datatable to your dropdown list. You can set valuemember as teh categoryid and display member as category-name in your dropdown binding.
Then when saving send the dropdown.datavalue to the car table insert script.
You can set Category-Name as "Display member" and Category-ID as "Value member" for combo box. So combo box will list with Category Name and "cmbCategotryName.SelectedValue" will get you Category ID.
public void FillCategory()
        {
            DataTable dtbl = new DataTable();
            dtbl.Columns.Add("CategoryID");
            dtbl.Columns.Add("CategoryName");
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dtbl.NewRow();
                dr["CategoryID"] = i.ToString();
                dr["CategoryName"] = "Category" + i.ToString();
                dtbl.Rows.Add(dr);
            }
            cmbCategotryName.DataSource = dtbl;
            cmbCategotryName.DisplayMember = "CategoryName";
            cmbCategotryName.ValueMember = "CategoryID";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillCategory();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string CategoryID = cmbCategotryName.SelectedValue.ToString();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of nandithaa
nandithaa
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sivakugan
sivakugan

ASKER

Do i have to have two different object data sources to do that?
No, i just posted 2 methods, u can do which one suites u....
Thanks