0

我使用 3 层架构插入数据库。我不知道我应该在 .cs 文件中的按钮单击事件上写什么代码。有人可以帮我吗?

扩展名.cs

    public static DbParameter CreateAndSetParameter(this DbCommand cmd,string parameterName,DbType dbtype,int size,ParameterDirection direction)
{
    DbParameter p = cmd.CreateParameter();
    p.ParameterName = parameterName;
    p.DbType =dbtype;
    p.Size = size;
    p.Direction = direction;
    cmd.Parameters.Add(p);
    return p;
}
public static DbParameter CreateAndSetParameter(this DbCommand cmd, string parameterName, DbType dbtype, int size,object value)
{
    DbParameter p = cmd.CreateParameter();
    p.ParameterName = parameterName;
    p.DbType = dbtype;
    p.Size = size;
    p.Direction = ParameterDirection.Input;
    p.Value = value;
    cmd.Parameters.Add(p);
    return p;
}

DataGeneric.cs

     public static int AddSlider(string @Imgname,string @Imgalt)
    {
    int rows=-1;
    string Query="insert into [slider](ImageName,ImageAlt) values(@Imgname,@Imagealt)";
    DbCommand cmd = DataGeneric.CreateCommand();
    cmd.CommandText = Query;
    cmd.CreateAndSetParameter("@Imgname",DbType.String,50,Imgname);
    cmd.CreateAndSetParameter("@Imgalt", DbType.String, 50, Imgalt);
    rows = DataGeneric.ExecuteNonQuery(cmd);
    return rows;
    }

设计:

    ImageName:<asp:TextBox id="txt_name" runat="server" /><br />
    ImageAlt:<asp:TextBox ID="txt_alt" runat="server" />
    <asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Insert" />

代码:

    protected void btn_Click(object sender, EventArgs e)
{
    ????????????
}
4

1 回答 1

0
protected void btn_Click(object sender, EventArgs e)
{

   DataGeneric.AddSlider(txt_name.Text,txt_alt.Text);

}

由于 Addslider 是一个静态方法,您可以使用类名直接调用该方法

修改你的addslider方法

public static int AddSlider(string Imgname,string Imgalt)
{
int rows=-1;
SqlConnection conn = new SqlConnection("connection string");
conn.Open();
string Query="insert into [slider](ImageName,ImageAlt) values(@Imgname,@Imagealt)";
DbCommand cmd = DataGeneric.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = Query;
cmd.CreateAndSetParameter("@Imgname",DbType.String,50,Imgname);
cmd.CreateAndSetParameter("@Imgalt", DbType.String, 50, Imgalt);
rows = DataGeneric.ExecuteNonQuery(cmd);
conn.Close();
return rows;
}
于 2013-05-04T13:27:10.527 回答