随手整理的常用代码(关于asp.net 2.0和javascript,还有样式表)

索引:
1、为DataGrid行添加删除按钮(带确认功能)
2、如何实现在DataGrid中多行选择或选择所有行
3、如何实现,在DataGrid中使用下拉列表作为数据显示与修改的界面,要求与数据相联系
4、如何将DataGrid导出为Excel文件
5、如何在弹出对话框时保持页面有内容
6、窗口A:点击按钮打开窗口B,并将参数A传递到窗口B
   窗口B:点击按钮关闭窗口B,并将参数B传递到窗口A
7、如何远程查看错误
8、多个按钮共享一个事件
9、在javascript中对页面上的控件进行操作
10、常见客户端事件
11、关于MultiView控件和view子控件
12、文件上传与浏览完整代码
13、关于样式表
14、关于javascript的一些知识
17、用老的方式连接数据库
18、打开数据库连接的好习惯
=================================================================================


1、为DataGrid行添加删除按钮(带确认功能)
   首先需要添加模板列,在模板中添加按钮“btDelete”
   代码:
  private void dgShow_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   switch(e.Item.ItemType)
   {
    case ListItemType.Item:
    case ListItemType.EditItem:
    case ListItemType.AlternatingItem:
     Button    myDeleteButton = (Button)e.Item.FindControl("btnDelete");
     myDeleteButton.Text = "删除此行";
     myDeleteButton.Attributes.Add("onclick", "return confirm('您真的要删除第 " + e.Item.ItemIndex.ToString() + " 行吗?');");
     break;
   }
  }


2、如何实现在DataGrid中多行选择或选择所有行
   1} 新建一个模板列,在模版列的header行插入一个checkbox控件"cbAll",用于选择所有行,在item行插入一checkbox控件"cbSelect",用于选择单行
   2} 在html界面,为check_all控件添加事件OnCheckChanged = "CheckAll",代码如下

  public void CheckAll(object sender, System.EventArgs e)
  {
   CheckBox cbAll = (CheckBox)sender;
   if(cbAll.Text=="全选")
   {
    foreach(DataGridItem dgi in dgShow.Items)
    {
     CheckBox cb = (CheckBox)dgi.FindControl("cbSelect");
     cb.Checked = cbAll.Checked;
    }
   }
  }
   3} 在页面上添加一个按钮用于删除所选列,其代码如下  

  private void btnDelete_Click(object sender, System.EventArgs e)
  {
   foreach(DataGridItem dgi in dgShow.Items)
   {
    CheckBox cb = (CheckBox)dgi.FindControl("cbSelect");
    if(cb.Checked)
    {
     //以下执行删除操作
     int nID = int.Parse(dgi.Cells[0].Text);
     string strSql = "delete from tbStudentinfo where studentid="+nID;
     ExecuteSql(strSql);
    }
   }
   dgShow.CurrentPageIndex = 0;
   BindData();
  }


3、如何实现,在DataGrid中使用下拉列表作为数据显示与修改的界面,要求与数据相联系
   1} 添加模板列,在item行与edit行中都建立一个下拉列表,分别用于显示与编辑,其中item行中的下拉列表应设为disable
   2} 在数据绑定时添加下列代码:

   foreach(DataGridItem dgi in dgShow.Items)
   {
    //以下绑定非编辑状态下拉列表
    DropDownList ddI = (DropDownList)dgi.FindControl("ddlSexI");
    if(ddI!=null)
    {
     bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
     if(bSex)
      ddI.SelectedIndex = 0;
     else
      ddI.SelectedIndex = 1;
    }
    //以下绑定编辑状态下拉列表
    DropDownList ddE = (DropDownList)dgi.FindControl("ddlSexE");
    if(ddE!=null)
    {
     bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
     if(bSex)
      ddE.SelectedIndex = 0;
     else
      ddE.SelectedIndex = 1;
    }
    
   }
   3} 手动编写DataGrid的UpdateCommand处理过程

  private void dgShow_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string strStudentID = e.Item.Cells[0].Text;//处于非编辑状态
   string strName = ((TextBox)(e.Item.Cells[1].Controls[0])).Text;//处于编辑状态
   string strPass =((TextBox)(e.Item.Cells[2].Controls[0])).Text;
   string strSex = ((DropDownList)(e.Item.FindControl("ddlSexE"))).SelectedItem.Value;
   string strBirthday =((TextBox)(e.Item.Cells[4].Controls[0])).Text;
   string strEmail =((TextBox)(e.Item.Cells[5].Controls[0])).Text;
   string strSql = "update tbStudentinfo set StudentName='"+strName+"',StudentPass='"+strPass+"'";
   strSql +=",Sex="+strSex+",Birthday='"+strBirthday+"',Email='"+strEmail+"' where studentid="+strStudentID+"";
   ExecuteSql(strSql);
   dgShow.EditItemIndex = -1;
   BindData();

  }

4、如何将DataGrid导出为Excel文件
   1} 添加一个导出按钮btnMIME
   2} 代码:

 private void btnMIME_Click(object sender, System.EventArgs e)
  {
   Response.ContentType = "application/vnd.ms-excel";
          Response.Charset = "";
   this.EnableViewState = false;
   System.IO.StringWriter sw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
   dgShow.RenderControl(hw);
   Response.Write(sw.ToString());
   Response.End();
  }

   3} 如果DataGrid用了分页功能,则代码有所变化

  private void btnMIME_Click(object sender, System.EventArgs e)
  {
   Response.ContentType = "application/vnd.ms-excel";
              Response.Charset = "";
   this.EnableViewState = false;
   System.IO.StringWriter sw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
   int nCur = dgShow.CurrentPageIndex;
   int nSize = dgShow.PageSize;
   
   dgShow.AllowPaging = false;
   BindData();
    
   dgShow.Columns[7].Visible =false;
   dgShow.RenderControl(hw);
   dgShow.Columns[7].Visible =true;
   
   //以下恢复分页
   dgShow.AllowPaging = true;
   dgShow.CurrentPageIndex = nCur;
   dgShow.PageSize = nSize;
   BindData();
   Response.Write(sw.ToString());
   Response.End();
  }


5、如何在弹出对话框时保持页面有内容
    在ASP.NET中,用后台代码中弹出对话框,一般的解决办法都是用Response.Write写一段脚本代码来弹出对话框,
  可问题是当对话框弹出后,页面却一片空白。这里讲述的办法就是在弹出对话框的同时保持页面的显示。
  【原理】
    在页面上放置一隐藏控件,并在页面最后放上一段脚本代码,脚本代码检测隐藏控件的value是否为空,若不为空
  则弹出对话框显示信息,否则什么也不做。
    后台代码在需要的时候修改隐藏控件的value,这样当页面传到用户那时,最后的脚本代码将执行并弹出对话框。
  【注意事项】
   (1)隐藏控件必须是HTML控件,否则JavaScript无法找到。
   (2)后台代码要修改隐藏控件的值,隐藏控件自然得加上runat=”server” 标记。
   (3)在弹出对话框后,记得把隐藏控件的value置空,否则刷新的时候又会弹出来了。
   (4)脚本代码一定得放在隐藏控件的后面,否则同样找不到。
  【实现】
 <body MS_POSITIONING="GridLayout">
 <form id="Form1" method="post" runat="server">
  <asp:TextBox id="manuInput" runat="server"></asp:TextBox>
  <asp:Button id="Button1" runat="server" Text="对话框"></asp:Button>
  <INPUT id="passTxt" type="hidden" runat="server"><!—隐藏控件->
 </form>
 <script language=javascript>
  if( document.all("passTxt").value!="" )
   {
   alert( document.all("passTxt").value );
   document.all("passTxt").value=""; //这句可不能掉哟!
  }
 </script>
 </body>
 后台代码(例子中只列出Button1的响应事件)
 private void Button1_Click(object sender, System.EventArgs e)
 {
  passTxt.Value = manuInput.Text;
 }

6、窗口A:点击按钮打开窗口B,并将参数A传递到窗口B
   窗口B:点击按钮关闭窗口B,并将参数B传递到窗口A
   窗口A:控件:Textbox1、Button1
   html:在末尾写上:即当textbox1的内容不为空时才弹出窗口B
      <script language=javascript>
   if( document.all("Textbox1").value!="" )
   {
    window.open("B_FORM.aspx","bform");
   }
      </script>
   窗口B:控件:Textbox1、Button1
          html:Button1属性添加“OnClientClick="form_close()"”
  在末尾写上:
      <script language=javascript>
   document.all("Textbox1").value = window.opener.document.all("textbox1").value;
   function form_close()
   {
       window.opener.document.all("textbox1").value = document.all("Textbox1").value;
       window.close();
   }
            </script>

7、如何远程查看错误
   编辑web.config  
   <configuration>  
         <system.web>  
               <customErrors>   defaultRedirect="genericerror.htm"   mode="Off">  
                     <error   statusCode="500" redirect="InternalError.htm"/>  
               </customErrors>  
         </system.web>  
   </configuration>

8、多个按钮共享一个事件
    Public Sub BtnClick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim b As New Button
        b = sender
        Select Case (b.ID)
            Case "JXB"
                MultiView1.ActiveViewIndex = -1
            Case "JXBBGS"
                MultiView1.ActiveViewIndex = -1
            Case "JXBGLK"
                MultiView1.ActiveViewIndex = -1
            Case "JXBPXK"
                MultiView1.ActiveViewIndex = -1
            Case "JXBJXD"
                MultiView1.ActiveViewIndex = 0
            Case "JXBDQD"
                MultiView1.ActiveViewIndex = 1
            Case "JXBYKD"
                MultiView1.ActiveViewIndex = 2
            Case "JXBTXD"
                MultiView1.ActiveViewIndex = 3
            Case "JXBZCD"
                MultiView1.ActiveViewIndex = 4
        End Select
        BZ_Click(b)
    End Sub

9、在javascript中对页面上的控件进行操作

 document.getElementById("控件名").属性 = ""
 

10、常见客户端事件

 1}、onblur:控件失去焦点时
 2}、onfocus:控件得到焦点时
 3}、onclick:
 4}、onchange:控件的值发生改变时
 5}、onkeydown:用户按键时
 6}、onkeypress:用户按文字或数字键时
 7}、onkeyup:用户松开键时
 8}、onmouseover:鼠标移到控件上时
 9}、onserverclick:当控件被单击时抛出一个serverclick事件


11、在MultiView控件中的view子控件中添加按钮,并给CommandName属性赋以下值

 1}、NextView:点击可切换到下一view
 2}、PrevView:点击可切换到上一view
 3}、SwitchViewById:点击可切换到CommandArgument指定的view
 4}、SwitchViewByIndex:点击可切换到CommandArgument指定的view


12、文件上传与浏览完整代码

Imports System.IO
Partial Class fu1
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim str As String = ""
        If FileUpload1.HasFile Then
            Try
                str &= "Uploading file: " & FileUpload1.FileName
                '保存文件
                FileUpload1.SaveAs("e://qnpcweb//" & FileUpload1.FileName)
                '显示信息
                str &= "<br />Save As: " = FileUpload1.PostedFile.FileName
                str &= "<br />File Type: " & FileUpload1.PostedFile.ContentType
                str &= "<br />File Length (bytes): " & FileUpload1.PostedFile.ContentLength
                str &= "<br />PostedFile File Name: " & FileUpload1.PostedFile.FileName
            Catch ex As Exception
                str &= "<br /><b>Error</b><br />Unable to save e://qnpcweb//" & FileUpload1.FileName & "<br />" & ex.Message
            End Try
        Else
            str = "No file uploaded !"
        End If
        Label1.Text = str
        Label2.Text = ""
    End Sub

    '从文本文件中读取每一行(非中文)
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim str As String = "<u>File: " & FileUpload1.FileName & "</u><br />"
        If FileUpload1.HasFile Then
            Try
                Dim sreader As New StreamReader(FileUpload1.FileContent)
                Dim strline As String = ""
                Do
                    strline = sreader.ReadLine()
                    str &= "<br />" & strline
                Loop While strline <> ""
            Catch ex As Exception
                str &= "<br /><b>Error</b><br />Unable to display " & FileUpload1.FileName & "<br />" & ex.Message
            End Try
        Else
            str = "No file upload !"
        End If
        Label1.Text = ""
        Label2.Text = str
    End Sub
End Class

13、关于样式表

 1}、如果放在页面中,需要放在head元素中,用<style></style>包含

 2}、格式1:>>> 可自动作用于该页面上所有该类型的元素

  元素类型{属性1:值1;
    属性2:值2;
    ...}
  
 3}、格式2:>>> 可作用于该页面上所有该类型的指定为该自定义类名的元素(class="自定义类名")

  元素类型.自定义类名{属性1:值1;
           属性2:值2;
        ...}
  
 4}、格式3:>>> 可作用于该页面上所有取该自定义类的元素

  .自定义类名{属性1:值1;
       属性2:值2;
       ...}
  
 5}、格式4:>>> 可作用于该页面上指定id的元素

  #元素id{属性1:值1;
   属性2:值2;
   ...}
  
14、document.getElementById("对象id") 返回该对象
    document.getElementByTagName("标签名") 返回该类对象对应的一个数组
    object.getAttribute("属性名") 取出对象的指定属性
    object.setAttribute("属性名","属性值") 给指定对象的指定属性赋值
    if(sonething) 与 if(something != null)完全等价
    可以用this替代调用javasvript代码的对象
    在页面加载时执行:window.onload = javascript程序名;


15、当一个超链接被点击时调用一个javascript程序,并且返回一个false值,则该超链接不会被执行

16、节点的节点类型:node.nodeType
       元素节点 =1
       属性节点 =2
       文本节点 =3

17、用老的方式连接数据库

Imports System.Data.OleDb
Partial Class dataapp1
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cnn1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/MY.NET/WEBAPP01/Northwind.mdb")
        Dim myapt As New OleDbDataAdapter("select * from 产品", cnn1)
        Dim dataset1 As New Data.DataSet
        myapt.Fill(dataset1, "产品")
        Dim mytab As New Data.DataTable
        mytab = dataset1.Tables("产品")
        GridView1.DataSource = mytab
        GridView1.DataBind()
    End Sub
End Class


18、打开数据库连接的好习惯

try
 打开连接
 数据处理
finally
 关闭连接
end try

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值