新闻页面参数传递(非编程方式绑定数据)
1、创建sqlexpress数据库:mydb。建一news表,表内字段如下:ID、NewsTitle、Author、CreateTime、Content。
具体字段及方法是:
2、新建网站:mynews
3、新建页面:InsertNews.aspx,单击“插入”按钮时,完成如下事件:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection mycn = new SqlConnection();
string constr = "data source=(local)\\sqlexpress;initial catalog=mydb;integrated security=true";
mycn.ConnectionString = constr;
mycn.Open();
string cmstr = "insert into news(NewsTitle,Author,CreateTime,NewsContent) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')";
SqlCommand mycm = new SqlCommand(cmstr, mycn);
int i = mycm.ExecuteNonQuery();
if (i == 1)
Response.Write("success!");
mycn.Close();
}
完成数据插入到news表中
4、新建页面:NewsList.aspx,页面上安排数据源控件sqldatasource1 和 gridview1 两个控件。设置如下:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:mydbConnectionString %>"
SelectCommand="SELECT * FROM [news]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="id"
DataNavigateUrlFormatString="ShowNews.aspx?id={0}" DataTextField="NewsTitle"
HeaderText="标题" />
<asp:BoundField DataField="CreateTime" HeaderText="CreateTime"
SortExpression="CreateTime" />
</Columns>
</asp:GridView>