问题:从DB中获取一个新闻种类的datatable,并将其绑定在 DropDownList中,最后可以根据DropDownList
来添加不同新闻种类的新闻
DB:
界面;
后置代码:
protected void Page_Load(object sender, EventArgs e)
{
//判断session里面是否存在管理员
if (Session["admin"] != null)
{
if (!Page.IsPostBack)
{
//绑定新闻分类
DataTable dt = new CategoryManager().GetAllCategory();
ddlCategory.DataSource=dt;
//绑定key值
ddlCategory.DataTextField="name";
//绑定value值
ddlCategory.DataValueField="id";
ddlCategory.DataBind();
}
}
else
{
//未登录
Response.Redirect("login.aspx");
}
}
进行添加新闻的代码:
//添加新闻按钮
protected void btnAdd_Click(object sender, EventArgs e)
{
News n = new News();
//获取DropDownList的value值
n.CaID = ddlCategory.SelectedValue.ToString();
//获取DropDownList的key值
n.CaID = ddlCategory.SelectedItem.ToString();
//这种方法也可以获取DropDownList的value值
n.CaID = ddlCategory.Text;
n.Title = txtTitle.Text.Trim();
n.Content = FreeTextBox1.Text;
bool b= new NewsManager().AddNews(n);
if (b)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('新闻添加成功!');</script>");
}
else
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('新闻添加失败!');</script>");
}
//清空标题和内容
Clear();
}
//清空标题和内容
private void Clear()
{
txtTitle.Text = "";
FreeTextBox1.Text = "";
}
在HTML页面中生成的DropDownList的代码
<p>新闻分类:<select name="ctl00$ctl00$ContentPlaceHolder1$M_ContentPlaceHolder$ddlCategory" id="ctl00_ctl00_ContentPlaceHolder1_M_ContentPlaceHolder_ddlCategory">
<option value="27">IT新闻</option>
<option value="28">时事新闻</option>
<option value="29">科技新闻</option>
<option value="30">体育新闻</option>
</select>
</p>