先占楼,楼主在线等.马上好.
====================
以下代码已测试通过.楼主只需要:
1.新建一个aspx文件,把原来的全删除,把下面的代码全复制过去.
2.改改数据库连接字符串
就可以使用:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
//数据库连接字符串,楼主这里应该改为自己的
private string connectionString = @"data source=.\sql2000;database=shiyu;uid=sa;pwd=sa;";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//显示两个Dropdown中的数据
DataSet ds = new DataSet();
new SqlDataAdapter("select distinct brand from table1", connectionString).Fill(ds, "brand");
new SqlDataAdapter("select distinct model from table1", connectionString).Fill(ds, "model");
this.Dropband.DataSource = ds.Tables["brand"];
this.Dropmodel.DataSource = ds.Tables["model"];
this.DataBind();
}
}
//保存
protected void BtnSave_Click(object sender, EventArgs e)
{
//保存数据
//1.先取table1中的id
SqlCommand cmd = new SqlCommand("select top 1 [id] from table1 where brand=@brand and model=@model");
cmd.Parameters.AddWithValue("@brand", Dropband.SelectedValue);
cmd.Parameters.AddWithValue("@model", Dropmodel.SelectedValue);
cmd.Connection = new SqlConnection(connectionString);
cmd.Connection.Open();
object result = cmd.ExecuteScalar();
cmd.Connection.Close();
if (result == null)
{
LblResult.Text = "没有找到对应的brand和model的id";
return;
}
//2.insert到table2中
int id = (int)result;//id是int数据类型,楼主可以改为自己的类型
cmd.CommandText = "insert into table2 values (@id,@color,@price)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@color", Txtcolor.Text);
cmd.Parameters.AddWithValue("@price", Txtprice.Text);
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
this.LblResult.Text = "操作完毕";
}
catch (Exception ex)
{
this.LblResult.Text = "操作出现错误:" + ex.Message;
}
finally
{
cmd.Connection.Close();
}
}
</script>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Brand:<asp:DropDownList ID="Dropband" runat="server" DataTextField="brand" DataValueField="brand">
</asp:DropDownList>
Model:<asp:DropDownList ID="Dropmodel" runat="server" DataTextField="model" DataValueField="model">
</asp:DropDownList>
Color:<asp:TextBox ID="Txtcolor" runat="server"></asp:TextBox>
Price:<asp:TextBox ID="Txtprice" runat="server"></asp:TextBox>
<asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSave_Click" />
<asp:Label ID="LblResult" runat="server" Text=""></asp:Label>
</form>
</body>
</html>