天天看点

asp.net 小技巧

asp.net 小技巧
asp.net 小技巧
asp.net 小技巧
asp.net 小技巧

=================================================================================================================================

http://www.w3school.com.cn/                 查找html 标记

、===============================================================================================================================

DataSet ds = CC.GetDataSet("select * from tb_News", "tbNews");

        DataRow[] row = ds.Tables["tbNews"].Select("id=" + Request.QueryString["id"]);

        foreach (DataRow rs in row)

        {

            this.Page.Title = rs["title"].ToString();

            this.labTitle.Text = rs["title"].ToString();

            this.txtContent.Text ="  "+ rs["content"].ToString();

        }

=================================================================================================================================

Attributes 是个集合,可以用 string 来标识某个元素,它里面的元素都是代表一个个事件的。

1

Button1.Attributes[

"onclick"

] = 

"ISCheck()"

;

这就是说 Button1 的 OnClick(鼠标单击)事件交给 ISCheck() 这个方法来处理。

、、==================================================================================================================

foreach (DataRow dr in ds.Tables[0].Rows)

        {

            if (!dr.IsNull(0))

            {

                if (P_Int_max <= Convert.ToInt32(dr[0]))

                {

                    P_Int_max = Convert.ToInt32(dr[0]);

                    P_Str_date = Convert.ToDateTime(dr[1]).ToShortDateString();

                }

            }

        }

======================================================================================================================

 protected void SaveFUC()

    { 

        //创建动态增加数组

        ArrayList AL = new ArrayList();

        foreach (Control C in tabFU.Controls)//tabFU是table控件

        {

            if (C.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTableRow")

            {

                HtmlTableCell HTC = (HtmlTableCell)C.Controls[0];

                foreach (Control FUC in HTC.Controls)

                {

                    //判断该控件是否为上传控件(FileUpLoad),如果是,则添加到ArrayList中

                    if (FUC.GetType().ToString() == "System.Web.UI.WebControls.FileUpload")

                    {

                        FileUpload FU = (FileUpload)FUC;

                        AL.Add(FU);

                    }

                }

            }

        }

        //将保存在数组ArrayList中的所有上传控件(FileUpLoad),添加到缓存中,命名为“FilesControls”

        Session.Add("FilesControls",AL); 

    }

=================================================================================================================================

//绑定文件创建时间

    protected void DDLBind()

    {

        //打开与数据库的连接

        SqlConnection myConn = CC.GetConnection() ;

        myConn.Open();

        //查询文件创建时间

        SqlDataAdapter dapt=new SqlDataAdapter("select distinct fileUpDate from tb_files", myConn);

        DataSet ds=new DataSet();

        //填充数据集

        dapt.Fill(ds, "files");

        //绑定下拉菜单

        this.ddlUD.DataSource = ds.Tables["files"].DefaultView;

        this.ddlUD.DataTextField = ds.Tables["files"].Columns[0].ToString(); 

        this.ddlUD.DataBind();

        //释放占用的资源

        ds.Dispose();

        dapt.Dispose();

        myConn.Close();

    }

//==========================================================================================

protected void imgbtnDelete_Click(object sender, ImageClickEventArgs e)//注意e和下一段的e是不同的

    {

        //获取imgbtnDelete的ImageButton对象

        ImageButton imgbtn = (ImageButton)sender;

        //引用imgbtnDelete控件的父控件上一级控件

        GridViewRow gvr = (GridViewRow)imgbtn.Parent.Parent;

        //获取文件真实姓名

        string sqlStr = "select fileTrueName from tb_files where fileID='" + gvFiles.DataKeys[gvr.RowIndex].Value.ToString() + "'";

================================================================================================

protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            //鼠标移动到GridView控件的任意行时,该行自动变成指定颜色

            e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#BEC9F6';this.style.color='buttontext';this.style.cursor='default';");

            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='';this.style.color=''");

            //双击行打开新页

            e.Row.Attributes.Add("ondblclick", "window.open('FileInfo.aspx?id="+e.Row.Cells[0].Text+"')");

        }

    }

==============================================================================================

/// <param name="strSql">sqlStr执行的SQL语句</param>

    public void ExecNonQuery(string strSql)

    {

        try

        {

            myConn = GetConnection();//与数据库连接

            myCmd = new SqlCommand();//初始化SqlCommand类对象

            myCmd.Connection = myConn;

            myCmd.CommandText = strSql;

            if (myCmd.Connection.State != ConnectionState.Open)

            {

                myCmd.Connection.Open();//打开与数据库的连接

            }

            myCmd.ExecuteNonQuery();//执行Sql操作,并返回受影响的行数

        }

        catch (Exception ex)

        {

            throw new Exception(ex.Message, ex);

        }

        finally

        {

            if (myCmd.Connection.State == ConnectionState.Open)

            {//断开连接,释放资源

                myCmd.Connection.Close();

                myConn.Dispose();

                myCmd.Dispose();

            }

        }

    }

================================================================================================

public string ExecScalar(string strSql)

    {

        try

        {

            myConn = GetConnection();//与数据库连接

            myCmd = new SqlCommand();//初始化SqlCommand类对象

            myCmd.Connection = myConn;

            myCmd.CommandText = strSql;

            if (myCmd.Connection.State != ConnectionState.Open)

            {

                myCmd.Connection.Open();//打开与数据库的连接

            }

            //使用SqlCommand对象的ExecuteScalar方法返回第一行第一列的值

            strSql=Convert.ToString(myCmd.ExecuteScalar());

            return strSql ;

        }

        catch (Exception ex)

        {

            throw new Exception(ex.Message, ex);

        }

        finally

        {

            if (myCmd.Connection.State == ConnectionState.Open)

            {//断开连接,释放资源

                myConn.Dispose();

                myCmd.Connection.Close();

                myCmd.Dispose();

            }

        }

    }

=========================================================================================

 strSelect = "select * from tb_Article where ArticleID='" + Convert.ToInt32(Request["ArticleID"].ToString()) + "'";

        DataTable dsTable = dbObj.GetDataSet(strSelect, "tbArticle");

        intBlogId = int.Parse(dsTable.Rows[0]["BlogID"].ToString());//发表文章的博客ID代号

        strSubject = dsTable.Rows[0]["Subject"].ToString();         //文章主题

=========================================================================================

 <asp:GridView ID="gvArticle" runat="server" AllowPaging="True" AutoGenerateColumns="False"

                                                CellPadding="4" Font-Size="9pt" Width="500px" OnRowDeleting="gvArticle_RowDeleting" OnPageIndexChanging="gvArticle_PageIndexChanging" OnRowDataBound="gvArticle_RowDataBound">

                                                <Columns>

                                                    <asp:BoundField DataField="Subject" HeaderText="文章主题" />

                                                    <asp:BoundField DataField="Content" HeaderText="文章内容" />

                                                    <asp:BoundField DataField="Time" HeaderText="创作时间" />

                                                    <asp:HyperLinkField DataNavigateUrlFields="ArticleID" DataNavigateUrlFormatString="EditContent.aspx?id={0}"

                                                        HeaderText="编辑" Text="编辑" />

                                                    <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />

                                                </Columns>

                                            </asp:GridView>

=======================================================================================================

protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

if ((e.Row.Cells[0].Text).Length > 6)

{

e.Row.Cells[0].Text = (e.Row.Cells[0].Text).Substring(0, 6) + "…";//截取文章主题

}

            if ((e.Row.Cells[1].Text).Length > 6)

            {

                e.Row.Cells[1].Text = (e.Row.Cells[1].Text).Substring(0, 6) + "…";//截取文章内容

            }

            DateTime dt = Convert.ToDateTime(e.Row.Cells[2].Text.ToString());

            e.Row.Cells[2].Text = dt.ToShortDateString();//格式化创建时间

((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick","return confirm('确定要删除吗?')");//为GridView控件的删除按钮添加确认对话框

}

}

===============================================================================================================

<td colspan="2" style="width: 16px; height: 18px; text-align: center">

                                <asp:DropDownList ID="ddlSex" runat="server">

                                    <asp:ListItem>男</asp:ListItem>

                                    <asp:ListItem>女</asp:ListItem>

                                </asp:DropDownList><span style="font-size: 9pt">&nbsp;</span></td>

===============================================================================================================

int.Parse(dsTable.Rows[0]["ID"].ToString());//保存用户ID代号

=================================================================================================================

Response.Write("<script language=javascript>window.open('AdminManage.aspx');window.close();</script>");

Response.Write("<script>window.close();location='javascript:history.go(-1)';</script>");

=================================================================================================================

<td style="width: 54px; height: 2px">

                                            <asp:Button ID="btnSearch" runat="server" Text="查找" OnClick="btnSearch_Click" Font-Size="9pt" /></td>

                                        <td style="width: 111px; height: 2px">

                                            <asp:LinkButton ID="lnkbtnAdd" runat="server" Font-Size="9pt" PostBackUrl="~/Admin/Register.aspx" Font-Underline="False" ForeColor="Blue">添加管理员</asp:LinkButton></td>

==============================================================================================================

 <asp:TemplateField HeaderText="注册时间">

                                            <ItemTemplate> 

                                            <%#Convert.ToDateTime(DataBinder.Eval(Container.DataItem, "RegTime").ToString()).ToLongDateString() %>

                                            </ItemTemplate>

                                        </asp:TemplateField>

==============================================================================================================

private SqlCommand CreateCommand(string procName, SqlParameter[] prams)

    {

        // 确认打开连接

        this.Open();

        SqlCommand cmd = new SqlCommand(procName, con);

        cmd.CommandType = CommandType.Text;     //执行类型:命令文本

        // 依次把参数传入命令文本

        if (prams != null)

        {

            foreach (SqlParameter parameter in prams)

                cmd.Parameters.Add(parameter);

        }

        // 加入返回参数

        cmd.Parameters.Add(

            new SqlParameter("ReturnValue", SqlDbType.Int, 4,

            ParameterDirection.ReturnValue, false, 0, 0,

            string.Empty, DataRowVersion.Default, null));

        return cmd;

    }

 public int RunProc(string procName, SqlParameter[] prams)

    {

        SqlCommand cmd = CreateCommand(procName, prams);

        cmd.ExecuteNonQuery();

        this.Close();

        //得到执行成功返回值

        return (int)cmd.Parameters["ReturnValue"].Value;

    }

 public DataSet RunProcReturn(string procName, SqlParameter[] prams, string tbName)

    {

        SqlDataAdapter dap = CreateDataAdaper(procName, prams);

        DataSet ds = new DataSet();

        dap.Fill(ds, tbName);

        this.Close();

        //得到执行成功返回值

        return ds;

    }

public DataSet FindModuleByID(ModuleManage modulemanage, string tbName)

    {

        SqlParameter[] prams = {

   data.MakeInParam("@moduleid",  SqlDbType.NVarChar, 50, modulemanage.ModuleID+"%"),

};

        return (data.RunProcReturn("select * from tb_Module where 版块编号 like @moduleid", prams, tbName));

    }

===============================================================================================================

 public int AddHost(HostManage hostmanage)

    {

        SqlParameter[] prams = {

   data.MakeInParam("@hostname",  SqlDbType.NVarChar, 50, hostmanage.HostName),

                                        data.MakeInParam("@moduleid",  SqlDbType.NVarChar, 50, hostmanage.ModuleID),

                data.MakeInParam("@hostpwd",  SqlDbType.NVarChar, 50,hostmanage.HostPwd),

                data.MakeInParam("@tname",  SqlDbType.NVarChar, 20, hostmanage.TName),

                data.MakeInParam("@sex",  SqlDbType.Bit, 1, hostmanage.Sex),

                data.MakeInParam("@birthday",  SqlDbType.SmallDateTime, 8, hostmanage.Birthday),

                data.MakeInParam("@tel",  SqlDbType.NVarChar, 20, hostmanage.Tel),

                                        data.MakeInParam("@mobile",  SqlDbType.NVarChar, 20, hostmanage.Mobile),

                data.MakeInParam("@qq",  SqlDbType.BigInt, 8,hostmanage.QQ),

                data.MakeInParam("@photo",  SqlDbType.NVarChar, 200, hostmanage.Photo),

                data.MakeInParam("@email",  SqlDbType.NVarChar, 50, hostmanage.Email),

                data.MakeInParam("@faddress",  SqlDbType.NVarChar, 100, hostmanage.FAddress),

                data.MakeInParam("@raddress",  SqlDbType.NVarChar, 100, hostmanage.RAddress),

                                        data.MakeInParam("@index",  SqlDbType.NVarChar, 50, hostmanage.Index),

};

        return (data.RunProc("INSERT INTO tb_Host (版主,版块编号,密码,真实姓名,性别,出生日期,联系电话,手机,QQ号,头像,Email,家庭住址,联系地址,个人首页,版主权限) "

            + "VALUES (@hostname,@moduleid,@hostpwd,@tname,@sex,@birthday,@tel,@mobile,@qq,@photo,@email,@faddress,@raddress,@index,'" +hostpop + "')", prams));

    }

public int RunProc(string procName, SqlParameter[] prams)

    {

        SqlCommand cmd = CreateCommand(procName, prams);

        cmd.ExecuteNonQuery();

        this.Close();

        //得到执行成功返回值

        return (int)cmd.Parameters["ReturnValue"].Value;

    } 

  private SqlCommand CreateCommand(string procName, SqlParameter[] prams)

    {

        // 确认打开连接

        this.Open();

        SqlCommand cmd = new SqlCommand(procName, con);

        cmd.CommandType = CommandType.Text;     //执行类型:命令文本

        // 依次把参数传入命令文本

        if (prams != null)

        {

            foreach (SqlParameter parameter in prams)

                cmd.Parameters.Add(parameter);

        }

        // 加入返回参数

        cmd.Parameters.Add(

            new SqlParameter("ReturnValue", SqlDbType.Int, 4,

            ParameterDirection.ReturnValue, false, 0, 0,

            string.Empty, DataRowVersion.Default, null));

        return cmd;

    }

=============================================================================================================

=============================================================================================================

为理解AutoPostBack ,我们需要知道,什么是PostBack。  

那么,什么是AutoPostBack , Autopostback是一种机制(自动根据Web控件的一些事件,将页面自动发回服务器。在一些Web控件中,称为auto post back属性。如果设置为true ,当此控件的某事件发生时,将发送一个request到服务器。  

例如:  

Dropdown Box (Combo box)控件的属性AutoPostBack。如果我们将其设置为true ,当用户在组合框中选择不同的值时,被触发的事件将发送一个request给服务器。   

根据上面的理解,我的理解是,autopostback 是用在一个控件中的值变换会带来另一个控件值变换时,需要设置为true

它的AutoPostBack属性默认为False,如果不把属性改为True,他的SelectedIndexChanged()事件中的代码就不会执行(SelectedIndexChanged()是选控件中的项所触发的事件)

===============================================================================================================

<asp:DataList ID="dlImage" runat="server"   RepeatDirection="Horizontal" RepeatColumns="5" OnDeleteCommand="dlImage_DeleteCommand">

asp.net 小技巧

===========================================================================================================

TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用来输入数量的TextBox控件 

            int count = Int32.Parse(otb.Text);//获得用户输入的数量值

==========================================================================================================

asp.net 小技巧

============================================================================================================

asp.net 小技巧

==============================================================================================================

asp.net 小技巧

=============================================================================================================

asp.net 小技巧

============================================================================================================

asp.net 小技巧

==============================================================================================================

asp.net 小技巧

===============================================================================================================

asp.net 小技巧

=================================================================================================================

asp.net 小技巧

===============================================================================================================

asp.net 小技巧

============================================================================================================

asp.net 小技巧

===============================================================================================================

asp.net 小技巧

==============================================================================================================

asp.net 小技巧

等价

=============================================================================================================