Perfil de 网风网风空间FotosBlogListas Herramientas Ayuda

Blog


26 diciembre

.net 主题与样式

理论上上来说,不同的主题中的样式表和SKIN文件的结构都应该是完全相同的。
3)  设置你要应用主题的控件的css样式名为css中定义的样式名(比如column、gradient)
设置你要应用主题的服务器控件的SkinId为Skin文件中定义的skinid(比如login、create等),这样在Skin中定义的控件属性会自动附加到当前的控件上(内部也是使用CSS实现的)
4)  应用主题,有三种办法      
       全局主题:在Web.config中<system.web>中添加<pages StyleSheetTheme ="ThemeName"/>节,这样在整个应用中都会自动应用名为ThemeName 的主题
       页面主题:在ASPX文件顶部加入:<%@ Page Language="C#" StylesheetTheme=" ThemeName " %>,这样当前页面都会应用名为ThemeName 的主题,或者在ASPX_CS中加(Page_Load方法)入如下代码 Page. StyleSheetTheme = “ThemeName”; 
       角色主题:需要使用masterpage 来辅助实现 ,通过User.IsInRole(“RoleName”) 来判断用户是否属于某个角色,然后决定使用何种主题(Page. StyleSheetTheme = “ThemeName”);当然,使用这种办法还可以应用用户选择的主题
       如果你仍然感觉迷惑,请查看 Quick Start 。
(二)  工作原理
    不同的主题和皮肤之间的不同主要是页面和页面中的控件的样式(包括字体、段落、背景、边框等等)、部分图片的不同。
    传统的完全使用CSS来表现不同的主题的方案,在处理图片和图片按钮的地方往往心有余而力不足。而在aspnet2.0里面一切都已经变得简单。
    主题和皮肤是 dotnet framework2.0内建支持的,服务器控件添加了SkinId属性,Page类也添加了Theme 和 StyleSheetTheme 属性,其目的就是优雅的支持Skin。在应用指定了主题之后,相关的页面会自动链接位于主题目录下的css文件和skin文件,css的用法跟传统的用法没有什么区别,而skin文件则以一种类似于css的方式工作,指定了SkinId的服务器控件会自动从skin文件中加载并附加匹配的属性或样式(最常用的是Image 和ImageButton的ImageUrl属性,这样做可以使页面在不同的主题下)---这是在服务器端完成的。由于skin文件在使用后是缓存在内存中的,所以效率不会有问题。
 
(三)  Theme 和 StylesheetTheme 的区别
    基本上,本文前面所有的 StyleSheetTheme 都可以替换为 Theme ,我猜想区别是使用 Theme 时位于主题文件夹中的 样式表(CSS)文件不会被应用到主题中,但是根据我的测试,发现两种情况下生成的页面中,只有<link href=’’>这一节的位置不同,一个出现在<Title>标记前面,一个则是后面。
(四)  优雅之处
a)         完全Framework内建的支持、不再需要复杂的编程,甚至不再需要编程;
b)        在vs2005中有非常友好的设计时支持,也就是说,在设计的时候你就可以看到某种主题的效果;
c)        学习曲线很平缓,如果你熟悉CSS的话,则更加没有难度。
-----------------
a、页面里相同的控件使用不同的样式:在该控件后面加skinID
  b、把定义好的theme应用到整个页面:在该页的Page页签里加上属性theme=“theme名称”
  c、把定义好的theme应用到整个站点:在web.config文件system.web的配置节中加上<pages theme="theme名称">
  d、动态的更换站点的样式(主题、皮肤):在Page_PreInit事件中写代码,Page.Theme = "...";
  e、控件中应用样式的优先级:a、StyleSheetTheme引用的风格[优先级最低]
 
                           b、代码设定的控件属性(覆盖StyleSheetTheme)
 
                           c、Theme引用的风格(覆盖前面2个) [优先级最高]
  f、让某个控件不应用theme里面定义的风格:更改属性EnableTheming=false即可
 
141 /**//// <summary>
  142 /// 获取当前的表达式对所选列进行排序
  143 /// </summary>
  144 protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo)
  145 {
  146 sortOrder = "";
  147 sortOrderNo = -1;
  148 for (int i = 0; i < sortColumns.Length; i++)
  149 {
  150 if (sortColumns[i].StartsWith(sortColumn))
  151 {
  152 sortOrderNo = i + 1;
  153 if (AllowMultiColumnSorting)
  154 {
  155 sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim();
  156 }
  157 else
  158 {
  159 sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC");
  160 }
  161 }
  162 }
164 /**//// <summary>
  165 /// 绘制升序降序的图片
  166 /// </summary>
  167 protected void DisplaySortOrderImages(string sortExpression, GridViewRow dgItem)
  168 {
  169 string[] sortColumns = sortExpression.Split(",".ToCharArray());
  170
  171 for (int i = 0; i < dgItem.Cells.Count; i++)
  172 {
  173 if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
  174 {
  175 string sortOrder;
  176 int sortOrderNo;
  177 string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
  178 SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo);
  179 if (sortOrderNo > 0)
  180 {
  181 string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl);
  182
  183 if (sortImgLoc != String.Empty)
  184 {
  185 Image imgSortDirection = new Image();
  186 imgSortDirection.ImageUrl = sortImgLoc;
  187 dgItem.Cells[i].Controls.Add(imgSortDirection);
189 }
  190 else
  191 {
  192
  193 if (AllowMultiColumnSorting)
  194 {
  195 Literal litSortSeq = new Literal();
  196 litSortSeq.Text = sortOrderNo.ToString();
  197 dgItem.Cells[i].Controls.Add(litSortSeq);
  198
  199 }
  200 }
  201 }
  202 }
  203 }
  204
  205 }

关于GridView的学习日记3

============================
GridView系列(一)排序列头加箭头
GridView.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div >
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1"
            OnRowCreated="GridView1_RowCreated" OnSorting="GridView1_Sorting" PageSize="5">
            <Columns>
                <asp:BoundField DataField="CompanyName" HeaderText="公司名称" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="联系人" SortExpression="ContactName" />
                <asp:BoundField DataField="Address" HeaderText="地址" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="城市" SortExpression="City" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT * FROM [Customers]"></asp:SqlDataSource>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <br />
        d</div>
    </form>
</body>
</html>
GridView.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GridView : System.Web.UI.Page
{
    string sortexp = "";//排序表达式
    string sortdir = "";//排序方向
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell tc in e.Row.Cells)
            {
                //这种方法直接新加一个控件,也可以换成图片
                //Label ls = new Label();
                //ls.Font.Name = "Webdings";
                //ls.Text = "5";
                //tc.Controls.Add(ls);
                  if (tc.Controls.Count > 0 )//这里要判断一下此时是不是已经生成了linkbutton
                string s1 = ((LinkButton)tc.Controls[0]).Text;
                ((LinkButton)tc.Controls[0]).Text = s1.Replace(s1, s1 + "<font face='Webdings'>5</font>");
               
                if (tc.Controls.Count > 0 && tc.Controls[0].GetType().ToString() == "System.Web.UI.WebControls.DataControlLinkButton")
                {
                   
                    if (((LinkButton)tc.Controls[0]).CommandArgument==sortexp)
                    {
                        //Label l = new Label();
                        //l.Font.Name = "Webdings";
                        //if (sortdir == "Ascending")
                        //{
                        //    l.Text = "5";
                        //}
                        //else
                        //{
                        //    l.Text = "6";
                        //}
                        //tc.Controls.Remove(ls);
                        //tc.Controls.Add(l);
                        string s2 = ((LinkButton)tc.Controls[0]).Text;
                        if (sortdir=="Descending")
                        {
                            ((LinkButton)tc.Controls[0]).Text = s2.Replace("5", "6");
                        }
                   }
                    }
                }
            }
        }
    }
   
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        sortexp = e.SortExpression.ToString();
        sortdir = e.SortDirection.ToString();
   
    }
}
=====================================================
Asp.net中复合控件的一些学习心得
在.net 2.0中有System.Web.UI.WebControls.CompositeControl,使得编写的复合控件在使用时有更友好的界面
以前在做复合控件时最常见的是以下代码
public class LabelTextBox :WebControl, INamingContainer
{
public string Text {
get {
object o = ViewState["Text"];
if (o == null)
return String.Empty;
return (string) o;
      }
set { ViewState["Text"] = value; }
   }
public string Title {
get {
object o = ViewState["Title"];
if (o == null)
return String.Empty;
return (string) o;
      }
set { ViewState["Title"] = value; }
   }
protected override void CreateChildControls()
   {
Controls.Clear();
CreateControlHierarchy();
ClearChildViewState();
   }
protected virtual void CreateControlHierarchy()
   {
TextBox t = new TextBox();
Label l = new Label();
t.Text = Text;
l.Text = Title;
Controls.Add(l);
Controls.Add(t);
   }
}
 
重点是这一句public class LabelTextBox :WebControl, INamingContainer
继承了WebControl类和实现ImamingContainer了接口
但是这样做成的复合控件在使用时设计界面很不友好,在2.0中新增了一个System.Web.UI.WebControls.CompositeControl
这样在作用控件的时候就不会有设计的障碍了,代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CompositeControl
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:LabelTextBox runat=server></{0}:LabelTextBox>")]
    public class LabelTextBox : System.Web.UI.WebControls.CompositeControl
    {
        public string Text
        {
            get
            {
                object o = ViewState["Text"];
                if (o == null)
                return String.Empty;
                return (string)o;
            }
            set
            {
                ViewState["Text"] = value;
            }
        }
        public string Title11
        {
            get
            {
                object o = ViewState["Title"];
                if (o == null)
                    return String.Empty;
                return (string)o;
            }
            set
            {
                ViewState["Title"] = value;
            }
        }
        protected override void CreateChildControls()
        {
            Controls.Clear();
            CreateControlHierarchy();
            ClearChildViewState();
        }
        protected virtual void CreateControlHierarchy()
        {
            TextBox t = new TextBox();
            Label l = new Label();
            t.Text = Text;
            l.Text = Title11;
            Controls.Add(l);
            Controls.Add(t);
        }
    }
}
===============================================
<%@ Page language="C#" %>
<script runat="server">
  void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    // If multiple buttons are used in a GridView control, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Add")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);
           
      // Retrieve the row that contains the button clicked
      // by the user from the Rows collection.
      GridViewRow row = CustomersGridView.Rows[index];
           
      // Create a new ListItem object for the customer in the row.    
      ListItem item = new ListItem();
      item.Text = Server.HtmlDecode(row.Cells[2].Text);
           
      // If the customer is not already in the ListBox, add the ListItem
      // object to the Items collection of the ListBox control.
      if (!CustomersListBox.Items.Contains(item))
      {
        CustomersListBox.Items.Add(item);
      }          
    }
  }
  void CustomersGridView_RowCreated(Object sender, GridViewRowEventArgs e)
  {
   
    // The GridViewCommandEventArgs class does not contain a
    // property that indicates which row's command button was
    // clicked. To identify which row's button was clicked, use
    // the button's CommandArgument property by setting it to the
    // row's index.
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Retrieve the LinkButton control from the first column.
      LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];
         
      // Set the LinkButton's CommandArgument property with the
      // row's index.
      addButton.CommandArgument = e.Row.RowIndex.ToString();
    }
  }
   
</script>
<html>
  <body>
    <form runat="server">
       
      <h3>GridView RowCommand Example</h3>
           
      <table width="100%">        
        <tr>               
          <td width="50%">
                   
            <asp:gridview id="CustomersGridView"
              datasourceid="CustomersSource"
              allowpaging="true"
              autogeneratecolumns="false"
              onrowcommand="CustomersGridView_RowCommand"
              onrowcreated="CustomersGridView_RowCreated" 
              runat="server">
               
              <columns>
                <asp:buttonfield buttontype="Link"
                  commandname="Add"
                  text="Add"/>
                <asp:boundfield datafield="CustomerID"
                  headertext="Customer ID"/>
                <asp:boundfield datafield="CompanyName"
                  headertext="Company Name"/>
                <asp:boundfield datafield="City"
                  headertext="City"/>        
              </columns>
               
            </asp:gridview>
                   
          </td>
                   
          <td valign="top" width="50%">
                   
            Customers: <br/>
            <asp:listbox id="CustomersListBox"
              runat="server"/>
                   
          </td> 
        </tr>     
      </table>
           
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [City] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server"/>
           
    </form>
  </body>

关于GridView的学习日记2

=======================================
=======================================
请教:GridView绑定后并设置了AutoGenerateEditButton="True" ,并出现了相应的编辑按钮。但是当点击编辑按钮却未能出现预料的编辑状态?
请教何解:
.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" OnRowEditing="GridView1_RowEditing" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="ParentID" SortExpression="ParentID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ParentID") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ParentID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Pic" SortExpression="Pic">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Pic") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("Pic") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CreateDate" SortExpression="CreateDate">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CreateDate") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Bind("CreateDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField />
            </Columns>
        </asp:GridView>
        &nbsp;
   
    </div>
    </form>
</body>
</html>
.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default5 : System.Web.UI.Page
{
    Luoxp.OA.Config Conn = new Luoxp.OA.Config();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }
    }
    #region GetDataSet
    private DataSet GetDataSet(string sql)
    {
        string constring = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        SqlDataAdapter sda = new SqlDataAdapter(sql, constring);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        return ds;
    }
    #endregion
    #region BindData
    private void BindData()
    {
        string sql = "select * from news_Sort where parentid=10";
        DataSet ds = GetDataSet(sql);
        this.GridView1.DataSource = ds;
        this.GridView1.DataBind();
    }
    #endregion
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
    }
}

我在2005里面试了一下,没用模板列,自动生成的列,然后加编辑列,点编辑状态会改变的啊
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True"
                                DataKeyNames="ID" DataSourceID="SqlDataSource1" OnRowEditing="GridView1_RowEditing">
                                <Columns>
                                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
                                    <asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number" />
                                </Columns>
                            </asp:GridView>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;
    }
试试这个
hoho
发现了
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;
        BindData();
    }
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class charge : System.Web.UI.Page
...{
    protected SqlCommand com;
    protected SqlDataReader reader;
    protected SqlConnection con;
    protected SqlDataAdapter da;
    protected DataSet ds;
    protected string sql, strsql, var_strsql;
    DataTable myTable;
    DataColumn col;
    Int32 i = 0;
    protected void Page_Load(object sender, EventArgs e)
    ...{
        if (!IsPostBack)
        ...{
            if (Request.QueryString["action"] == "edit")
            ...{
                lbID.Text = Request.QueryString["id"];
                show();
                show1.Visible = false;
                show2.Visible = false;
                show3.Visible = false;
                data.Visible = false;
                btn_ok.Text = "修改";
                txt_pi.Focus();
                btn_ok.Attributes.Add("onclick", "javascript: return confirm('你确定要修改吗?');");
            }
            else
            ...{
                lbl_sql.Text = "select * from charge";
                data.DataSource = CreateNewDataSource();
                data.DataBind();
                txt_pi.Focus();
            }
        }
    }
    Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    ...{
        //
        // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
        //
        InitializeComponent();
        base.OnInit(e);
    }
    /**//// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    ...{
        this.data.RowDeleting += new GridViewDeleteEventHandler(data_RowDeleting);
    }
 
    protected void data_RowDeleting(object sender, GridViewDeleteEventArgs e)
    ...{
        if (ViewState["myTable"] != null)
            myTable = (DataTable)ViewState["myTable"];
        DataRow[] rowfind = myTable.Select("row='" + data.Rows[e.RowIndex].Cells[0].Text.Trim() + "'");
        rowfind[0].Delete();
        ViewState["myTable"] = myTable;
        data.DataSource = myTable.DefaultView;                       //将ds对象中的表邦定到DataList控件
        data.DataBind();
    }
    #endregion
 
 
    protected void init_text()
    ...{
        txt_pi.Text = "";
        txt_des.Text = "";
        txt_cou.Text = "";
    }
    protected void Add1_Click(object sender, EventArgs e)
    ...{
        if (txt_pi.Text.Trim() != "")
        ...{
            data.DataSource = CreateDataSource();
            data.DataBind();
            init_text();
            this.txt_pi.Focus();
        }
        else
        ...{
            Response.Write("<Script>alert("PI编号不能为空");</Script>");
        }
    }
    System.Collections.ICollection CreateNewDataSource()  //建立内存数据库
    ...{
        DataTable myTable = new DataTable("myTable");
        col = myTable.Columns.Add("row", typeof(Int32));
        col = myTable.Columns.Add("pi", typeof(string));
        myTable.Columns.Add("remark", typeof(string));
        myTable.Columns.Add("charge", typeof(string));
        ViewState["myTable"] = myTable;
        DataView myView = new DataView(myTable);
        return myView;
    }
    System.Collections.ICollection CreateDataSource()
    ...{
        if (ViewState["myTable"] != null)    //实例化myTable
        ...{
            myTable = (DataTable)ViewState["myTable"];
        }
        DataRow NewRow = myTable.NewRow();
        Session["i"] = System.Convert.ToInt32(Session["i"]) + 1;
        NewRow["row"] = System.Convert.ToInt32(Session["i"]);
        NewRow["pi"] = " " + txt_pi.Text.Trim();
        NewRow["remark"] = " " + txt_des.Text.Trim();
        NewRow["charge"] = " " + txt_cou.Text.Trim();
        myTable.Rows.Add(NewRow);
        ViewState["myTable"] = myTable;
        DataView myView = new DataView(myTable);
        //myView.Sort = "modu_id";    //数据排序
        return myView;
    }

    protected void data_RowCommand(object sender, GridViewCommandEventArgs e)
    ...{
        if (e.CommandName == "select")   //单击编辑按钮时发生的事件
        ...{
            int index = Convert.ToInt32(e.CommandArgument);
            txt_row.Text = Convert.ToString(index + 1);
            txt_pi.Text = " " + data.Rows[index].Cells[1].Text.ToString().Trim();
            txt_des.Text = " " + data.Rows[index].Cells[3].Text.ToString().Trim();
            txt_cou.Text = " " + data.Rows[index].Cells[2].Text.ToString().Trim();

        }
    }
    protected void edit_Click(object sender, EventArgs e)
    ...{
        if (ViewState["myTable"] != null)
            myTable = (DataTable)ViewState["myTable"];
        DataRow[] rowfind = myTable.Select("row ='" + txt_row.Text.Trim() + "'");
        if (rowfind.Length > 0)
        ...{
            rowfind[0]["pi"] = txt_pi.Text.Trim();
            rowfind[0]["remark"] = txt_des.Text.Trim();
            rowfind[0]["charge"] = txt_cou.Text.Trim();
        }
        ViewState["myTable"] = myTable;
        data.DataSource = myTable.DefaultView;                       //将ds对象中的表邦定到DataList控件
        data.DataBind();
        init_text();
    }
    protected void data_RowCreated(object sender, GridViewRowEventArgs e)
    ...{
        //e.Row.Cells[0].Attributes.Add("onclick", "return confirm('您是否确定要删除这条信息');");
    }
    protected void del_Click(object sender, EventArgs e)
    ...{
        if (ViewState["myTable"] != null)
            myTable = (DataTable)ViewState["myTable"];
        DataRow rowindex = myTable.Rows[i];
        DataRow[] rowfind = myTable.Select("row='" + txt_row.Text.Trim() + "'");
        rowfind[0].Delete();
        ViewState["myTable"] = myTable;
        for (int x = 0; x < myTable.Rows.Count; x++)
        ...{
            rowindex = myTable.Rows[x];
            rowindex["row"] = x + 1;
        }
        data.DataSource = myTable.DefaultView;                       //将ds对象中的表邦定到DataList控件
        data.DataBind();
    }
    protected void show()
    ...{
        string a = Request.QueryString["id"];
        //lbl1.Text = Request.QueryString["action"];
        btn_ok.Text = "修改";
        SqlConnection con = DBCon.creatConnection();        //连接资料源
        string strSql = "select * from count_gs where id='" + a + "'";
        con.Open();
        com = new System.Data.SqlClient.SqlCommand(strSql, con);    //对资料库的查询、对存储过程的调用、返回特定表的直接请求
        SqlDataAdapter my = new SqlDataAdapter(strSql, con);  //DataAdapter物件充当资料库和ADO.NET物件模型中断开连接的物件之间的桥梁
        DataTable tbl = new DataTable();   //一旦从资料库中读出资料,并将其存在DataTable中,资料与伺服器的连接就断开
        //my.SelectCommand = com;   //指定命令物件以便从资料存储区检索行
        my.Fill(tbl);         //通过DataAdapter物件的Fill方法,把查询的结果存在DataTable中
        DataRow row = tbl.Rows[0];
        txt_pi.Text = System.Convert.ToString(row["pi"]).Trim();
        txt_des.Text = System.Convert.ToString(row["remark"]).Trim();
        txt_cou.Text = System.Convert.ToString(row["charge"]).Trim();

    }
    protected void btn_ok_Click(object sender, EventArgs e)
    ...{
        if (Request.QueryString["action"] == "add")
<img id="_7102_8089_Open_Image" onclick="this.style.display='none'; document.getElementById('_7102_8089_Open_Text').style.display='none'; document.getElementById('_7102_8089_Closed_Image').style.display='inline'; document.getElementById('_7102_8089_Closed_Text').style.display='inline';" align="top" alt="" src="http://images.csdn.net/syntaxhighlighting/Ou
============================

关于GridView的学习日记1

1.有什么好的方法能取得父控件GridView中绑定行(子GridView所在行)的DataKeys.也就是得到一个parendid的字段。
2.怎么实现 <FooterTemplate>在没有数据绑定的情况下也再现。目的是能够时时增加数据。

数据表类似:
http://www.microsoft.com/china/community/Column/30.mspx

CREATE TABLE [News_Sort] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[ParentID] [int] NOT NULL ,
[Name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Pic] [varchar] (2000) COLLATE Chinese_PRC_CI_AS NULL ,
[CreateDate] [datetime] NOT NULL CONSTRAINT [DF_News_Sort_CreateDate] DEFAULT (getdate()),
[Compositor] [int] NOT NULL CONSTRAINT [DF_News_Sort_Compositor] DEFAULT (0)
) ON [PRIMARY]
GO


.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Adm_NewsSort_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="MasterGridView" runat="server" AutoGenerateColumns="False" Width="500px" ShowFooter=true
      BorderWidth="1px" OnRowDataBound="MasterGridView_RowDataBound" DataKeyNames="id"
      ShowHeader="False" OnRowCancelingEdit="MasterGridView_RowCancelingEdit" OnRowDeleting="MasterGridView_RowDeleting" OnRowEditing="MasterGridView_RowEditing" OnRowUpdating="MasterGridView_RowUpdating" OnRowCommand="MasterGridView_RowCommand">
      <Columns>
       <asp:TemplateField>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox_Name" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <%# Eval("name")%>
            </ItemTemplate>
            <FooterTemplate>
               <asp:TextBox id="TextBox_Name_Input" runat="server"></asp:TextBox>
             </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox_Compositor" runat="server" Text='<%# Bind("Compositor") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <%# Eval("Compositor")%>
            </ItemTemplate>
             <FooterTemplate>
               <asp:TextBox id="TextBox_Compositor_Input" runat="server"></asp:TextBox>
             </FooterTemplate>      
        </asp:TemplateField>     
        <asp:TemplateField>
          <ItemTemplate>           
              <asp:GridView ID="DetailGridView" runat="server" ShowFooter=true  AutoGenerateColumns=false DataKeyNames="id,parentid" Width=200 OnRowDeleting="DetailGridView_RowDeleting" OnRowEditing="DetailGridView_RowEditing" OnRowUpdating="DetailGridView_RowUpdating" OnRowCancelingEdit="DetailGridView_RowCancelingEdit" OnRowCommand="DetailGridView_RowCommand">
                <HeaderStyle BackColor="#9999FF" />
                <Columns>
                  <asp:TemplateField>
                  <EditItemTemplate>
                        <asp:TextBox ID="TextBox_Name" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate><%# Eval("name")%></ItemTemplate>
                    <FooterTemplate>
                       <asp:TextBox id="TextBox_Name_Input" runat="server"></asp:TextBox>
                     </FooterTemplate>
                  </asp:TemplateField>  
                  <asp:TemplateField>
                  <EditItemTemplate>
                        <asp:TextBox ID="TextBox_Compositor" runat="server" Text='<%# Bind("Compositor") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate><%# Eval("Compositor")%></ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox id="TextBox_Compositor_Input" runat="server"></asp:TextBox>                        
                     </FooterTemplate>                        
                  </asp:TemplateField>  
                   <asp:TemplateField ShowHeader="False">
              <EditItemTemplate>
                  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                      Text="更新"></asp:LinkButton>
                  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                      Text="取消"></asp:LinkButton>
              </EditItemTemplate>
              <ItemTemplate>
                  <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Edit"
                      Text="编辑"></asp:LinkButton>
              </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField ShowHeader="False">
              <ItemTemplate>
                  <asp:LinkButton ID="LinkButton4" runat="server" CausesValidation="False" CommandName="Delete"
                      Text="删除" OnClientClick='return confirm("您确认要删除吗?");' ></asp:LinkButton>
              </ItemTemplate>
             
          </asp:TemplateField>    
          <asp:TemplateField>
          <FooterTemplate>
                <asp:LinkButton id="LinkButton5" runat="server" CommandName="Insert">增加</asp:LinkButton>
            </FooterTemplate>
          </asp:TemplateField>       
                </Columns>
              </asp:GridView>
          </ItemTemplate>
        </asp:TemplateField>         
          <asp:TemplateField ShowHeader="False">
              <EditItemTemplate>
                  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                      Text="更新"></asp:LinkButton>
                  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                      Text="取消"></asp:LinkButton>
              </EditItemTemplate>
              <ItemTemplate>
                  <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Edit"
                      Text="编辑"></asp:LinkButton>
              </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField ShowHeader="False">
              <ItemTemplate>
                  <asp:LinkButton ID="LinkButton4" runat="server" CausesValidation="False" CommandName="Delete"
                      Text="删除" OnClientClick='return confirm("您确认要删除吗?");' ></asp:LinkButton>
              </ItemTemplate>             
          </asp:TemplateField>
          <asp:TemplateField>
          <FooterTemplate>
                <asp:LinkButton id="LinkButton5" runat="server" CommandName="Insert">增加</asp:LinkButton>
             </FooterTemplate>
          </asp:TemplateField>
      </Columns>
    </asp:GridView>
       
        </div>
    </form>
</body>
</html>

.cs文件随后:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;

public partial class Adm_NewsSort_Default : System.Web.UI.Page
{
    Luoxp.OA.Config Conn = new Luoxp.OA.Config();
    SqlConnection cn1 = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Con"]);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }
    }
    protected void BindData()
    {
        SqlDataReader Dr = Conn.ExecuteReader_return_dr("select * from news_Sort where parentid=" + Session["User_Id"].ToString() + " order by compositor;");
        MasterGridView.DataSource = Dr;
        MasterGridView.DataBind();
        Dr.Close();
        Conn.Close();

    }
    protected void BindData1(string strId,GridView gridview)
    {
        cn1.Open();
        SqlCommand cmd = new SqlCommand("select * from news_Sort where parentid='" + strId + "' order by compositor;", cn1);
        SqlDataReader dr1 = cmd.ExecuteReader();
        gridview.DataSource = dr1;
        gridview.DataBind();
        dr1.Close();
        cmd.Dispose();
        cn1.Close();     
       

    }
    protected void MasterGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
              GridView oGridView = (GridView)e.Row.FindControl("DetailGridView");
              if (oGridView != null)
              {
                  BindData1(this.MasterGridView.DataKeys[e.Row.RowIndex].Values[0].ToString(), oGridView);  
              }
        }
    }
  
    protected void MasterGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {

        this.MasterGridView.EditIndex = e.NewEditIndex;
        BindData();

    }

    protected void MasterGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string strSql = "delete news_sort where id=" + this.MasterGridView.DataKeys[e.RowIndex].Value.ToString() + ";";
        Conn.ExecuteNonQuery_Sql(strSql);
        BindData();
    }

    protected void MasterGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.MasterGridView.EditIndex = -1;
        BindData();
    }

    protected void MasterGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string strTextbox_Name = ((TextBox)this.MasterGridView.Rows[e.RowIndex].FindControl("Textbox_Name")).Text;
        string strTextbox_Compositor = ((TextBox)this.MasterGridView.Rows[e.RowIndex].FindControl("Textbox_Compositor")).Text;
        string strSql = "update news_sort set name = '"+strTextbox_Name+"',Compositor='"+strTextbox_Compositor+"' where id="+this.MasterGridView.DataKeys[e.RowIndex].Values[0].ToString()+";";
        Conn.ExecuteNonQuery_Sql(strSql);
    }

    protected void DetailGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView a = (GridView)sender;
       if (a != null)
       {
           a.EditIndex = e.NewEditIndex;
           BindData1(a.DataKeys[e.NewEditIndex].Values[1].ToString(), a);          
         
       }

    }

    protected void DetailGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView a = (GridView)sender;
        string strSql = "delete news_sort where id=" + a.DataKeys[e.RowIndex].Values[0].ToString() + ";";
        Conn.ExecuteNonQuery_Sql(strSql);
        BindData1(a.DataKeys[e.RowIndex].Values[1].ToString(), a);
        //Response.Write("您要删除的记录是:<font color='red'>" + a.DataKeys[e.RowIndex].Value.ToString() + "</font>&nbsp;&nbsp;&nbsp;&nbsp;TODO:执行删除动作");
        // TODO:执行删除动作
    }
    protected void DetailGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridView a = (GridView)sender;
        if (a != null)
        {
            string strTextbox_Name = ((TextBox)a.Rows[e.RowIndex].FindControl("Textbox_Name")).Text;
            string strTextbox_Compositor = ((TextBox)a.Rows[e.RowIndex].FindControl("Textbox_Compositor")).Text;
            string strSql = "update news_sort set name = '" + strTextbox_Name + "',Compositor='" + strTextbox_Compositor + "' where id=" + a.DataKeys[e.RowIndex].Values[0].ToString() + ";";
            Conn.ExecuteNonQuery_Sql(strSql);
           
        }
       
    }
    protected void DetailGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView a = (GridView)sender;
        if (a != null)
        {
            a.EditIndex = -1;
            BindData1(a.DataKeys[e.RowIndex].Values[1].ToString(), a);
        }
    }
    protected void MasterGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert")
        {
             string strParentId = Session["User_Id"].ToString();               
             string strTextBox_Name_Input = ((TextBox)this.MasterGridView.FooterRow.FindControl("TextBox_Name_Input")).Text;
             string strTextBox_Compositor = ((TextBox)this.MasterGridView.FooterRow.FindControl("TextBox_Compositor_Input")).Text;
             string strSql = "insert into News_Sort(name,Parentid,Compositor) values('" + strTextBox_Name_Input + "','" + strParentId + "','" + strTextBox_Compositor + "');";
             Conn.ExecuteNonQuery_Sql(strSql);
             BindData();
        }
    }
    protected void DetailGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
         GridView a = (GridView)sender;
         if (a != null)
         {
             if (e.CommandName == "Insert")
             {
                 string strParentId = a.DataKeys[0].Values[1].ToString();
                 string strTextBox_Name_Input = ((TextBox)a.FooterRow.FindControl("TextBox_Name_Input")).Text;
                 string strTextBox_Compositor = ((TextBox)a.FooterRow.FindControl("TextBox_Compositor_Input")).Text;
                 string strSql = "insert into News_Sort(name,Parentid,Compositor) values('" + strTextBox_Name_Input + "','" + strParentId + "','" + strTextBox_Compositor + "');";
                 Conn.ExecuteNonQuery_Sql(strSql);
                 BindData1(strParentId, a);
             }
         }
    }
}

21 diciembre

web打印

1、控制"纵打"、 横打”和“页面的边距。
  (1)<script defer>
  function SetPrintSettings() {
   // -- advanced features
   factory.printing.SetMarginMeasure(2) // measure margins in inches
   factory.SetPageRange(false, 1, 3) // need pages from 1 to 3
   factory.printing.printer = "HP DeskJet 870C"
   factory.printing.copies = 2
   factory.printing.collate = true
   factory.printing.paperSize = "A4"
   factory.printing.paperSource = "Manual feed"
  
   // -- basic features
   factory.printing.header = "This is MeadCo"
   factory.printing.footer = "Advanced Printing by ScriptX"
   factory.printing.portrait = false
   factory.printing.leftMargin = 1.0
   factory.printing.topMargin = 1.0
   factory.printing.rightMargin = 1.0
   factory.printing.bottomMargin = 1.0
  }
  </script>
  
  (2)
  <script language="javascript">
    function printsetup(){
    // 打印页面设置
    wb.execwb(8,1);
    }
    function printpreview(){
    // 打印页面预览
      
    wb.execwb(7,1);
       
      
    }
  
    function printit()
    {
    if (confirm('确定打印吗?')) {
    wb.execwb(6,6)
    }
    }
    </script>
  </head>
  <body>
  <OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"
  
  height=0 id=wb name=wb width=0></OBJECT>
  <input type=button name=button_print value="打印"
  
  onclick="javascript:printit()">
  <input type=button name=button_setup value="打印页面设置"
  
  onclick="javascript:printsetup();">
  <input type=button name=button_show value="打印预览"
  
  onclick="javascript:printpreview();">
  <input type=button name=button_fh value="关闭"
  
  onclick="javascript:window.close();">
  
  ------------------------------------------------
  关于这个组件还有其他的用法,列举如下:
  WebBrowser.ExecWB(1,1) 打开
  Web.ExecWB(2,1) 关闭现在所有的IE窗口,并打开一个新窗口
  Web.ExecWB(4,1) 保存网页
  Web.ExecWB(6,1) 打印
  Web.ExecWB(7,1) 打印预览
  Web.ExecWB(8,1) 打印页面设置
  Web.ExecWB(10,1) 查看页面属性
  Web.ExecWB(15,1) 好像是撤销,有待确认
  Web.ExecWB(17,1) 全选
  Web.ExecWB(22,1) 刷新
  Web.ExecWB(45,1) 关闭窗体无提示
  
  2、分页打印
  <HTML>
  <HEAD>
  <STYLE>  
    P {page-break-after: always}
  </STYLE>
  </HEAD>
  <BODY>
  <%while not rs.eof%>
  <P><%=rs(0)%></P>
  <%rs.movenext%>
  <%wend%>
  </BODY>
  </HTML>
  
  3、ASP页面打印时如何去掉页面底部的路径和顶端的页码编号
  (1)ie的文件-〉页面设置-〉讲里面的页眉和页脚里面的东西都去掉,打印就不出来了。
  (2)<HTML>
  <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="YC">
  <script language="VBScript">
  dim hkey_root,hkey_path,hkey_key
  hkey_root="HKEY_CURRENT_USER"
  hkey_path="\Software\Microsoft\Internet Explorer\PageSetup"
  '//设置网页打印的页眉页脚为空
  function pagesetup_null()
    on error resume next
    Set RegWsh = CreateObject("WScript.Shell")
    hkey_key="\header"  
    RegWsh.RegWrite hkey_root+hkey_path+hkey_key,""
    hkey_key="\footer"
    RegWsh.RegWrite hkey_root+hkey_path+hkey_key,""
  end function
  '//设置网页打印的页眉页脚为默认值
  function pagesetup_default()
    on error resume next
    Set RegWsh = CreateObject("WScript.Shell")
    hkey_key="\header"  
    RegWsh.RegWrite hkey_root+hkey_path+hkey_key,"&w&b页码,&p/&P"
    hkey_key="\footer"
    RegWsh.RegWrite hkey_root+hkey_path+hkey_key,"&u&b&d"
  end function
  </script>
  </HEAD>
  
  <BODY>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/><p align=center>
  <input type="button" value="清空页码" onclick=pagesetup_null()> <input type="button" value="恢复页吗" onclick=pagesetup_default()><br/>
  
  </p>
  </BODY>
  </HTML>
  4、浮动帧打印
  <SCRIPT LANGUAGE=javascript>
  function button1_onclick() {
    var odoc=window.iframe1.document;
    var r=odoc.body.createTextRange();
    var stxt=r.htmlText;
    alert(stxt)
    var pwin=window.open("","print");
    pwin.document.write(stxt);
    pwin.print();
  }
  </SCRIPT>
  4、用FileSystem组件实现WEB应用中的本地特定打印
  <script Language=VBScript>
  function print_onclick //打印函数
  dim label
  label=document.printinfo.label.value //获得HTML页面的数据
  set objfs=CreateObject("Scripting.FileSystemObject") //创建FileSystem组件对象的实例
  set objprinter=objfs.CreateTextFile ("LPT1:",true) //建立与打印机的连接
  objprinter.Writeline("__________________________________") //输出打印的内容
  objprinter.Writeline("| |")
  objprinter.Writeline("| 您打印的数据是:"&label& " |”)
  objprinter.Writeline("| |")
  objprinter.Writeline("|_________________________________|")
  objprinter.close //断开与打印机的连接
  set objprinter=nothing
  set objfs=nothing // 关闭FileSystem组件对象
  end function
  </script>
  服务器端脚本:
  <%………
  set conn=server.CreateObject ("adodb.connection")
  conn.Open "DSN=name;UID=XXXX;PWD=XXXX;"
  set rs=server.CreateObject("adodb.recordset")
  rs.Open(“select ……”),conn,1,1
  ……….%> //与数据库进行交互
  HTML页面编码:
  <HTML>
  ………
  <FORM ID=printinfo NAME="printinfo" >
  <INPUT type="button" value="打印>>" id=print name=print > //调用打印函数
  <INPUT type=hidden id=text1 name=label value=<%=………%>> //保存服务器端传来的数据
  ………
  </HTML>
20 diciembre

C#中怎么创建ACCESS数据库文件?

1.
※新建工程
※进入解决方案->引用->添加引用
选择com标签 下的microsoft ado ext.2.8.....
->选择-> OK
※编码
//命令行工程代码如下
using System;
using ADOX;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\AccessDB\\NewMDB.mdb;" +
"Jet OLEDB:Engine Type=5");
Console.WriteLine("Database Created Successfully");
cat = null;
}
}
}
//asp.net代码如下
private void Page_Load(object sender, System.EventArgs e)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C://database//NewMDB.mdb;" +
"Jet OLEDB:Engine Type=5");
cat = null;
Response.Write("OK");
2.用sqlserver 的代码如下
SqlConnection conn=new SqlConnection("Server=lemoncat007;Uid=sa;Pwd=gtt");
conn.Open();
SqlCommand cmd=new SqlCommand("create database test",conn);
cmd.ExecuteNonQuery();
3 也可以创建一个Procedure 将创建数据库的语句写到里面然后执行
19 diciembre

C#实现SQLSERVER2000数据库备份还原的两种方法

C#实现SQLSERVER2000数据库备份还原的两种方法

 方法一(不使用SQLDMO):

 ///
 ///备份方法
 ///
 SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=sa;");
 
 SqlCommand cmdBK = new SqlCommand();
 cmdBK.CommandType = CommandType.Text;
 cmdBK.Connection = conn;
 cmdBK.CommandText = @"backup database test to disk='C:\ba' with init";

 try
 {
  conn.Open();
  cmdBK.ExecuteNonQuery();
  MessageBox.Show("Backup successed.");
 }
 catch(Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
 finally
 {
  conn.Close();
  conn.Dispose();
 }


 ///
 ///还原方法
 ///
 SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=sa;Trusted_Connection=False");
 conn.Open();

 //KILL DataBase Process
 SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='test'", conn);
 SqlDataReader dr;
 dr = cmd.ExecuteReader();
 ArrayList list = new ArrayList();
 while(dr.Read())
 {
  list.Add(dr.GetInt16(0));
 }
 dr.Close();
 for(int i = 0; i < list.Count; i++)
 {
  cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
  cmd.ExecuteNonQuery();
 }

 SqlCommand cmdRT = new SqlCommand();
 cmdRT.CommandType = CommandType.Text;
 cmdRT.Connection = conn;
 cmdRT.CommandText = @"restore database test from disk='C:\ba'";

 try
 {
  cmdRT.ExecuteNonQuery();
  MessageBox.Show("Restore successed.");
 }
 catch(Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
 finally
 {
  conn.Close();
 }

 

 

 方法二(使用SQLDMO):

 ///
 ///备份方法
 ///
 SQLDMO.Backup backup = new SQLDMO.BackupClass();
 SQLDMO.SQLServer server = new SQLDMO.SQLServerClass();
 //显示进度条
 SQLDMO.BackupSink_PercentCompleteEventHandler progress = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
 backup.PercentComplete += progress;

 try
 {
  server.LoginSecure = false;
  server.Connect(".", "sa", "sa");
  backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
  backup.Database = "test";
  backup.Files = @"D:\test\myProg\backupTest";
  backup.BackupSetName = "test";
  backup.BackupSetDescription = "Backup the database of test";
  backup.Initialize = true;
  backup.SQLBackup(server);
  MessageBox.Show("Backup successed.");
 }
 catch(Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
 finally
 {
  server.DisConnect();
 }
 this.pbDB.Value = 0;
 
  
 ///
 ///还原方法
 ///
 SQLDMO.Restore restore = new SQLDMO.RestoreClass();
 SQLDMO.SQLServer server = new SQLDMO.SQLServerClass();
 //显示进度条
 SQLDMO.RestoreSink_PercentCompleteEventHandler progress = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
 restore.PercentComplete += progress;

 //KILL DataBase Process
 SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=sa;Trusted_Connection=False");
 conn.Open();
 SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='test'", conn);
 SqlDataReader dr;
 dr = cmd.ExecuteReader();
 ArrayList list = new ArrayList();
 while(dr.Read())
 {
  list.Add(dr.GetInt16(0));
 }
 dr.Close();
 for(int i = 0; i < list.Count; i++)
 {
  cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
  cmd.ExecuteNonQuery();
 }
 conn.Close();
 
 try
 {
  server.LoginSecure = false;
  server.Connect(".", "sa", "sa");
  restore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
  restore.Database = "test";
  restore.Files = @"D:\test\myProg\backupTest";
  restore.FileNumber = 1;
  restore.ReplaceDatabase = true;
  restore.SQLRestore(server);
  MessageBox.Show("Restore successed.");
 }
 catch(Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
 finally
 {
  server.DisConnect();
 }
 this.pbDB.Value = 0;