I am creating an online news website. The user needs to login first so that they can add their news article. If the user logged in and create their own articles, how can I get their id and save it in the database along with their news article?
What I have tried:
public partial class Articles : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["NewsDataBaseConnectionString2"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCategory();
}
}
protected void btn_AddArticles_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(cs);
cn.Open();
SqlCommand cm = new SqlCommand("Insert into tbl_AddNews (User_id,title, category_id, details, photo, date) values(@Userid, @Title, @Category, @Details, @photo, @Date)", cn);
cm.Parameters.AddWithValue("@Title", txtbox_Title.Text);
cm.Parameters.AddWithValue("@Category", DropDownList1.SelectedValue);
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();
FileUpload1.PostedFile.SaveAs(Server.MapPath("Images\\") + strImg);
Response.Redirect("Articles.aspx");
}
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);
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "Category_id";
DropDownList1.DataTextField = "Category_Name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select Category--", "0"));
}
}
catch (Exception ex)
{
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "Something went wrong!." + ex.Message + "";
}
}
}