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 + "";
}