在Button事件上需要帮助

时间:2013-05-04 13:22:02

标签: c# sql 3-tier

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

Extension.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)
{
    ????????????
}

1 个答案:

答案 0 :(得分:0)

protected void btn_Click(object sender, EventArgs e)
{

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

}

由于Addslider是一种静态方法,您可以使用类名

直接调用该方法

修改你的addlider方法

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;
}