[转]Asp.net2.0新特性

asp.net 2.0中新增的AppendDataBoundItems

可以在执行数据绑定之前将项添加到 listcontrol 对象中。执行数据绑定之后,项集合中包含数据源中的项以及以前添加的项。如果不在绑定数据之前清除列表项,则为 true;如果在执行数据绑定之前清除项集合,则为 false。默认为 false。
比如

 

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="state" DataValueField="state">

    
<asp:ListItem Text="(Select a State)" Value="" />    

</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 

                   ConnectionString
="<%$ ConnectionStrings:pubsConnectionString %>" 

                   SelectCommand
="SELECT DISTINCT [state] FROM [authors]">

</asp:SqlDataSource>


 则为dropdownlist的第一项增加了一个要求用户选择的提示的信息,而在与sqldatasource或其他数据源绑定后,其不会消失

新增的web.config的默认namespace功能

在VB.NET中可以,但是在C#中没有测试成功!

在VB.NET中使用时还要在namespace 中设置autoImportVBNamespace="true"

<namespaces autoImportVBNamespace="true">

看上去这个题目比较长,但实际上,我在看资料时发现,这就是说,在asp.net 2.0中,只需要在web.config里定义你要用的那些namespace,则在aspx页面中就不需要再象1.1那样,用
<%@ import namespace="system.text" %>来引用了.比如,只需要在web.config中,以这样的方式就可以了
  <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.web>
<pages>
                  <namespaces>
                        <add namespace ="System.IO" />
  <add namespace="System.Text"/>

                  </namespaces>
</pages>

</configuration>

</system.web>

   这样一来,在所有的aspx页面中(注意不是codebehind页面),则不需要再用import的方法引入了.
   同样道理,在asp.net 1.1中,自定义控件的引用,在aspx页面中也是很麻烦的,在asp.net 2.0中,可以在web.config中这样定义
  <%@Register TagPrefix="uc" Namespace="xxxxxx" Assembly="xx" %>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
      <system.web>
            <pages>
                  <namespaces>
                        <add namespace ="System.IO" />
                        <add namespace="System.Text"/>
                  </namespaces>
                  <controls>
                       <add tagPrefix="uc" namespace="xx"
                             assembly="xxxx" />
                 </controls>
            </pages>
</configuration>
</system.web>


这样,在aspx页面中,只需要用uc来引用就可以了,十分方便

vs.net 2005中web.config智能感知丢失时

在vs.net 2005的web.config中,已经比vs.net 2003的智能感知有了很大的改进了,可以在web.config的编辑状态下提供智能感知了。但遇到一个问题,那就是当使用website->aspnet configuration进行对当前应用的
设置进行配置时,系统会自动更改web.config的内容,同时改变后,web.config功能就会丢失智能感知的
功能了。原因是什么了?我查阅了下资料,发现原来这个情况下,系统自动将原来的
<configuration>变为
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
   所以丢失了智能感知,当然,为了智能感知,你可以把它改回<configuration>,并不影响运行,
更彻底的方法是,修改c:\winnt\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\app_code\WebAdminPage.cs 文件,将第93行的
config.NamespaceDeclared = true;注释掉,改为
config.NamespaceDeclared = false;
这样,就可以确保彻底解决改问题了

GridView控件

GridView控件是Asp.net 1.1版本流行控件DataGrid的继承者,功能比DataGrid增强不少,但是也有很大的不同啊。将最近使用这个控件的经验同各位同学分享如下:
   1\掩藏字段的处理:DataGrid可以将字段直接设置为Visible=false,可以通过Cell[x].Text取到值。 GridView这个功能失效了,可以使用运行时来设定该列为掩藏。处理RowDataBound事件。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   e.Row.Cells[5].Visible = false;
}
   2\ 获取所选列的数据:DataGrid可以直接通过所选行来获取,GridView同样的代码无法运行。GridView 可以通过GridViewRow来获取。BtnAudit是模版列中的按钮。
GridViewRow grdRow = (GridViewRow)btnAudit.Parent.Parent;

string strId = grdRow.Cells[0].Text;
string memberId = grdRow.Cells[5].Text;
  3\ 最终删除一条数据之前进行确认,这个可以使用摸版列,在摸版列中放置按钮控件,其中有一个客户端事件onclientclick,这里可以写确认处理javascript脚本.例如:
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btnRefuse" runat="server" OnClick="btnRefuse_Click" Text="拒绝"  OnClientClick="return confirm(' 你真的要拒绝这个用户加入俱乐部?')"/>
                </ItemTemplate>
            </asp:TemplateField>

ASP.NET2.0中用Gridview控件操作数据

  在ASP.NET 2.0中,加入了许多新的功能和控件,相比asp.net 1.0/1.1,在各方面都有了很大的提高。其中,在数据控件方面,增加了不少控件,其中的Gridview控件功能十分强大。在本文中,将探讨Gridview控件中的一些功能特性和用法,如果各位读者对Gridview控件不大了解,可以通过《使用ASP.NET 2.0中的Gridview控件》一文,来对Gridview控件有个初步的认识。 

  1、使用Gridview插入新记录

  在Gridview控件中,可以实现插入新记录的操作(见《使用ASP.NET 2.0中的Gridview控件》)一文,但如果想实现在Gridview中,实现在Gridview控件的最后一行,提供一个空白行给用户输入要输入的记录,那无疑是很方便的。下面将介绍其实现方法。

  首先,我们打算在让用户进行选择,当用户需要新增一记录时,便点击新增按钮,之后在Gridview的最后一行里,显示一个空白行,让用户按字段进行输入,如下图所示:


 当用户决定不输入新空白记录时,可以按"cancel"按钮返回,该空白行消失。要实现这样的效果,我们可以充分利用Gridview的footer的模版功能进行自定义,因为有3列,所以,在每一列的footer模版中,定义如下:


<asp:Gridview ID="Gridview1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
 <asp:TemplateField>
  <ItemTemplate>
   <asp:Label ID="CustomerIDLabel" Runat="Server"><%# Eval("CustomerID") %></asp:Label>
  </ItemTemplate>
  <FooterTemplate>
   <asp:TextBox ID="CustomerIDTextBox" Runat="server"></asp:TextBox>
  </FooterTemplate>
 </asp:TemplateField>

 <asp:TemplateField>
  <ItemTemplate>
   <asp:Label ID="CompanyNameLabel" Runat="Server"><%# Eval("CompanyName") %></asp:Label>
  </ItemTemplate>
  <FooterTemplate>
   <asp:TextBox ID="CompanyNameTextBox" Runat="server"></asp:TextBox>
  </FooterTemplate>
 </asp:TemplateField>

 <asp:TemplateField>
  <FooterTemplate>
   <asp:DropDownList ID="ContactTitleDropDownList" Runat="server" DataSourceID="SqlDataSource2" DataTextField="ContactTitle" DataValueField="ContactTitle">
   </asp:DropDownList>
   <asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"
ConnectionString="server=localhost;uid=sa;password=xxx;database=northwind">
   </asp:SqlDataSource>

   <asp:Button ID="Button1" Runat="server" Text="Add" OnClick="Button1_Click" /> 
   <asp:Button ID="CancelButton1" Runat="server" Text="Cancel" OnClick="CancelButton1_Click" /> 
  </FooterTemplate>

 <ItemTemplate>
  <asp:DropDownList ID="ContactTitleDropDown" SelectedValue=’<%# Bind("ContactTitle") %>’ Runat="Server" DataSourceID="SqlDataSource3" DataTextField="ContactTitle" DataValueField="ContactTitle" ></asp:DropDownList>
  <asp:SqlDataSource ID="SqlDataSource3" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"
ConnectionString="server=localhost;uid=sa;password=xxxx;database=northwind" EnableCaching="True">
  </asp:SqlDataSource>
 </ItemTemplate>
 </asp:TemplateField>
</Columns>
</asp:Gridview>


  以上为Gridview的代码,可以看到,在第一,二列的<foottemplate>列中,分别提供了customerid和companyname两个文本框以供用户输入,在第三列的<footertemplate>列中,以dropdownlistbox的形式来显示contracttitle.。其中,请注意第三列的footertemplate中的add和cancel两个按钮的,它们的事件代码如下


<script runat="server"> 
void CancelButton1_Click(object sender, EventArgs e) 

 Gridview1.ShowFooter = false;

void AddButton1_Click(object sender, EventArgs e) 

 Gridview1.ShowFooter = true;
}

 //点add按钮时,将新增的记录更新到数据库中去
void Button1_Click(object sender, EventArgs e)

 TextBox customerID = Gridview1.FooterRow.FindControl("CustomerIDTextBox") as TextBox; 
 TextBox companyName = Gridview1.FooterRow.FindControl("CompanyNameTextBox") as TextBox;
 DropDownList ContactTitle = Gridview1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList;
 SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;
 SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;  
 SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue=ContactTitle.SelectedValue;
 SqlDataSource1.Insert();
}
</script>


  其中的cancel按钮的事件,用来取消显示Gridview的footer模版,因此设置showfooter属性为false,而addbutton1按钮,是当用户决定新增记录时点选的,此时将设置showfooter属性为true,以显示各列的foottemplate,从而达到显示新的一个空白行的目的。

  而在更新代码button1_click事件中,将首先使用Gridview1.footerrow.findcontrol的方法,将用户新增的各字段的值提取出来,然后分别赋值给sqldatasource的insertparameters集合(注意要一一对应),最后使用sqldatasource的insert方法,就可以成功向数据库增加一条新记录了。

  另外,为了在窗体加载时,显示数据库northwind中customers表的数据,需要设置sqldatsource1的属性,如下代码:


 <asp:SqlDataSource ID="SqlDataSource1" Runat="server"
InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)"
SelectCommand="SELECT top 5 [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]"
ConnectionString="server=localhost;uid=sa;password=XXXXX;database=northwind">
<InsertParameters>
<asp:Parameter Type="String" Name="CustomerID"></asp:Parameter>
<asp:Parameter Type="String" Name="CompanyName"></asp:Parameter>
<asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>


  其中,必须设置insertcommand和selectcommand属性,设置数据提取和插入的语句,并且要设置好insertparameters集合中,各字段的类型和名称即可。

  2、一次性更新所有的Gridview记录

  我们经常会遇到这样的情况,在Gridview中列出的所有记录中,有时要同时修改多条记录,并且将其保存到数据库中去。那么在Gridview中应该如何实现呢?在Gridview中,有两种实现的方法,下面分别进行介绍:

  先来看下第一种方法,本方法是使用sqldatasource来更新所有记录,但这个方法比较慢,因为每更新一条记录都要建立数据连接并执行updatecommand,会影响性能。其主要代码如下:

 

<script runat="server"> 
void Button1_Click(object sender, EventArgs e) 

 for (int i = 0; i < Gridview1.Rows.Count; i++) 
 { 
  GridviewRow row = Gridview1.Rows[i]; 
  SqlDataSource1.UpdateParameters[0].DefaultValue = ((TextBox)row.Cells[0].FindControl("TextBox2")).Text; 
  SqlDataSource1.UpdateParameters[1].DefaultValue = ((TextBox)row.Cells[1].FindControl("TextBox3")).Text; 
  SqlDataSource1.UpdateParameters[2].DefaultValue = Gridview1.DataKeys[i].Value.ToString(); 
  SqlDataSource1.Update(); 
 } 

</script> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head id="Head1" runat="server"> 
<title>Untitled Page</title> 
</head> 
<body> 
 <form id="form1" runat="server"> 
 <div> 
 <asp:Gridview ID="Gridview1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False"> 
 <Columns> 
 <asp:TemplateField SortExpression="CustomerID" HeaderText="CustomerID"> 
 <ItemTemplate> 
  <asp:TextBox Runat="server" Text=’<%# Bind("CustomerID") %>’ ID="TextBox1"></asp:TextBox> 
 </ItemTemplate> 

 </asp:TemplateField> 
  <asp:TemplateField SortExpression="CompanyName" HeaderText="CompanyName"> 
  <ItemTemplate> 
   <asp:TextBox Runat="server" Text=’<%# Bind("CompanyName") %>’ ID="TextBox2"></asp:TextBox> 
  </ItemTemplate> 
 </asp:TemplateField> 

 <asp:TemplateField SortExpression="ContactName" HeaderText="ContactTitle"> 
  <ItemTemplate> 
   <asp:TextBox Runat="server" Text=’<%# Bind("ContactTitle") %>’ ID="TextBox3"></asp:TextBox> 
  </ItemTemplate> 
 </asp:TemplateField> 
 </Columns> 

 </asp:Gridview> 
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" 
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]" 
UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @CustomerID" 
ConnectionString="server=localhost;uid=sa;password=xxxx;database=northwind"> 
<UpdateParameters> 
<asp:Parameter Type="String" Name="CompanyName"></asp:Parameter> 
<asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter> 
<asp:Parameter Type="String" Name="CustomerID"></asp:Parameter> 
</UpdateParameters> 
</asp:SqlDataSource> 
<asp:Button ID="Button1" Runat="server" Text="Button" OnClick="Button1_Click" />
</div> 
</form> 
</body> 
</html> 


  在上面的代码中,我们必须首先指定updateparameters参数集合,也就是指出要更新的是哪些字段,它们的类型是什么。之后并指出sqldatasource的updatecommand语句。而在更新按钮button1的CLICK事件中,将以遍历的形式,使用for循环,对Gridview中的每一行进行检查,将每个更新了的文本框的内容放到sqldatasouce的updateparameters参数中去,最后调用sqldatasource的update方法,完成更新。

  方法2使用的是首先遍历Gridview中的每一行,并且使用SQL语句,将要更新的内容连接起来,然后最后才使用command.ExecuteNonQuery()进行更新,效率高了,主要代码如下:


protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString);
 SqlCommand command = new SqlCommand("SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]", con);
 con.Open();
 Gridview1.DataSource = command.ExecuteReader();
 Gridview1.DataBind();
 con.Close();

}
protected void Button1_Click(object sender, EventArgs e)
{
 StringBuilder query = new StringBuilder();
 for (int i = 0; i < Gridview1.Rows.Count; i++)
 {
  GridviewRow row = Gridview1.Rows[i];
  string value1 = ((TextBox)row.Cells[0].FindControl("TextBox2")).Text.Replace("’", "’’");
  string value2 = ((TextBox)row.Cells[1].FindControl("TextBox3")).Text.Replace("’", "’’");
  string value3 = Gridview1.DataKeys[i].Value.ToString();
  query.Append("UPDATE [Customers] SET [CompanyName] = ’").Append(value1).Append("’ , [ContactTitle] = ’")
.Append(value2).Append("’ WHERE [CustomerID] = ’").Append(value3).Append("’;\n");
 }

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString);
 SqlCommand command = new SqlCommand(query.ToString(), con);
 con.Open();
 command.ExecuteNonQuery();
 con.Close(); 
}
}


  其中要特别注意一点的是,在vs.net 2005 beta 2开始,如果你在web.config中使用了数据库连接字符串的配置,那么应该按如下的方法去写:


<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=LIAO;Initial Catalog=Northwind;User ID=sa;Password=xxxx" providerName="System.Data.SqlClient"/>
</connectionStrings>


  然后在程序中如下进行读取:


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString);


GridView在更新数据时取得编辑状态下文本框内容和DataGrid也有不同

注意它的索引写法是:e.RowIndex

((TextBox)gridview.Rows[e.RowIndex].Cells[2].Controls[1]).Text;

 


如果DataSet没有数据  表头 HeadText根本不显示

GridView根据值的变化改变行列样式

 我看到论坛中有询问关于如何在GridView随某行某列值的改变时(这些值是空的或不是空的或是其它某些值等),其背景色及文本颜色也随之改变。这篇文章便论述这个问题。 

  根据某列的值改变其样式最好的方法是在GridView的DataRowBound事件中想办法。在GridView中的行绑定数据后将立即执行DataRowBound事件。DataRowBound事件使用GridViewRowEventargs类作为事件变量。通过事件变量你能够利用GridViewRowEventArgs属性操作已经绑定数据的行。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 GridViewRow row = e.Row;

  Row将返回TableRow类中的一个GridViewRow对象。

  绑定的Row有几种不同的类型。例如:DataRow, EmptyDataRow, Footer, Header, Pager 和 Separator。通过GridView的RowType属性可以得到当前行的行类型。RowType是一组DataControlRow枚举。

  看下面的代码示例,检测GridView列出的行是否为一个标准类型的行。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  //Do something!
 }

  可以使用Row的Cells属性得到其Cells,它将返回一个TableCellCollection对象。然后通过TableCellCollection索引得到特定的Cells。TableCellcollection索引将返回一个TabelCell对象,对应于Row中的一个Cell:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  string value = e.Row.Cells[0].Text;
 }

  现在你已经明白了如何得到GridView中某行某列的值,那么根据值的变化改变其样式就比较容易了。以下示例使用 Northwind 数据库,通过检测第四列(UnitPrice)的值是否大于10将其颜色改变为红色。

<%@ Page Language="C#"%>
<%@ Import Namespace="System.Drawing" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  if (Decimal.Parse(e.Row.Cells[3].Text) > 10)
   e.Row.Cells[3].BackColor = Color.Red;
 }
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
  <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
DataKeyNames="ProductID" OnRowDataBound="GridView1_RowDataBound">
  <Columns>
   <asp:BoundField ReadOnly="True" HeaderText="ProductID" InsertVisible="False" DataField="ProductID"
SortExpression="ProductID" />
   <asp:BoundField HeaderText="ProductName" DataField="ProductName" SortExpression="ProductName" />
   <asp:BoundField HeaderText="QuantityPerUnit" DataField="QuantityPerUnit" SortExpression="QuantityPerUnit" />
   <asp:BoundField HeaderText="UnitPrice" DataField="UnitPrice" SortExpression="UnitPrice" />
  </Columns>
 </asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice] FROM [Alphabetical list of products]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>" />

</div> 
</form> 
</body> 
</html>

Gridview控件如何获取表的主键

Gridview控件如何获取表的主键
怎么样像dataGrid控件通过datakeyfiled来取主键

***************************************

int id =(int) gv.DataKeys[(int)e.RowIndex].Value

GridView with CheckBoxes Auto-PostBack
Let‘s first see that how can we select the value of the GridView columns when we check the checkbox which is contained inside the GridView control. Here is the GridView HTML code: 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> 
<Columns>

<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />

<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />

<asp:TemplateField HeaderText="Select">

<ItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

 


As you can see I have two bound columns and one template column which contains the CheckBox. The AutoPostBack property of the CheckBox control is set to true which means the page will reload when you select a CheckBox. 

When the CheckBox is clicked the CheckBox_CheckedChanged event is fired. We need to implement this method in order to catch the row in which the CheckBox is checked. 


protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 
{

ClearCheckBoxes(); 

CheckBox checkbox = (CheckBox)sender;

checkbox.Checked = true; 

GridViewRow row = (GridViewRow)checkbox.NamingContainer;

DisplayMessage(row.Cells[1].Text);

}

 
One thing I like to point out is that when you select a different CheckBox then your first selection is not cleared. In order to make your previous selections clear you can implement a simple ClearCheckBoxes method which will iterate through the GridView control and clear all the CheckBoxes.   private void ClearCheckBoxes() 
{

foreach (GridViewRow row in GridView1.Rows)

{

CheckBox ch = (CheckBox) row.FindControl("CheckBox1");

ch.Checked = false; 

}

}

 


As, you can see that in ClearCheckBoxes method I am simply clearing all the CheckBoxes inside the GridView control. The DisplayMessage method simply assigns the CategoryName to the Label‘s Text property since CategoryName belongs to Cell[1].

 


 

posted @ 2006-04-29 15:30  李振波  阅读(2666)  评论(0编辑  收藏  举报