Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im creating a news website that i need to add news articles. If i add a news article i need to select category. The problem is when i save the news, I want to save the id of the selected category

What I have tried:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
             LoadCategory(); 
        }
    }


//add articles button
protected void btn_AddArticles_Click(object sender, EventArgs e)
    {

        SqlConnection cn = new SqlConnection(cs);
        cn.Open();
        SqlCommand cm = new SqlCommand("Insert into tbl_AddNews (title, category_id, details, photo, date) values(@Title, @Category, @Details, @photo, @Date)", cn);
        cm.Parameters.AddWithValue("@Title", txtbox_Title.Text);
        cm.Parameters.AddWithValue("@Category", Select1.Value);
        cm.Parameters.AddWithValue("@Details", txtbox_details.Text);
        string strImg = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
        cm.Parameters.AddWithValue("@photo", strImg);
        cm.Parameters.AddWithValue("@Date", DateTime.Now.ToString());
        cm.ExecuteNonQuery();
        cn.Close();
       
    }


//binding of dropdownlist
private void LoadCategory()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("select * from tbl_Category", con);
                con.Open();
                DataTable table = new DataTable();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(table);

                Select1.DataSource = table;
                Select1.DataValueField = "Category_id";
                Select1.DataTextField = "Category_Name";
                Select1.DataBind();
                Select1.Items.Insert(0, new ListItem("--Select Category--", "0"));
            }
        }

        catch (Exception ex)
        {
            Label1.ForeColor = System.Drawing.Color.Red;
            Label1.Text = "Something went wrong!." + ex.Message + "";
        }
Posted
Updated 27-Sep-17 1:01am

1 solution

use SelectedValue [^], DropdownList doesnt have a property called Value
Select1.SelectedValue; 
 
Share this answer
 
v3
Comments
Member 13432601 27-Sep-17 16:38pm    
Thank you very much
Karthik_Mahalingam 27-Sep-17 23:16pm    
welcome:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900