在GridView的EditItemTemplate中对控件进行数据绑定

2006年06月13日 5:18 下午  |  分类:Develop

gridview内置的编辑功能大大缩短了开发的周期,同时,利用它自带的这些功能大大节省了时间
以前在做开发时,利用gridview的编辑能时,在EditTemplate中添加一些诸如DropDownlist控件等,不知道如何给这些DropDownList绑定一些数据,
在.cs中用FindControls()怎么也找不到这些控件.只得作罢,今日又遇上此类问题,看来是躲不了了,只能解决它了.
因为GridView有一个RowCreated事件,无论是在生成行还是在编辑行时,都会触发该事件,所以,从它下手了,

protected void _gv_main_RowCreated(object sender, GridViewRowEventArgs e)
{
//这里注意Row的RowState属性的枚举
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList dd = (DropDownList)e.Row.FindControl("_dd_colorList");
string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor));
foreach (string color in colorArray)
{
ListItem item = new ListItem(color, color);
item.Attributes.Add("style", "background-color:" + color); dd.Items.Add(item);
}
}
}

这样就可以进行绑定了正在为此沾沾自喜时却发现,点击gridview的更新时,无法获取dropdownlist选中的值看来, 并未结束.
于是,在sqldatasource控件的Updating事件中来解决(因为gridview是绑定在一个sqldatasource上的)

protected void _gv_source_Updating(object sender, SqlDataSourceCommandEventArgs e) {
//找到当前编辑的行,并找到dropdownlist控件
DropDownList dd = (DropDownList)_gv_main.Rows[_gv_main.EditIndex].FindControl("_dd_colorList");
e.Command.Parameters["@color"].Value = dd.SelectedValue; //设定值
}

至此,问题得以解决。

为何FormView的更新功能会失效?

2006年06月13日 10:15 上午  |  分类:Develop

因为FromView的易用性,Blog后台管理的很多地方用到了它
一般是用GridView与FormView结合来使用
用GridView显示基本信息
点击GridView某一行后显示该条记录的详细信息
然后用FormView自带的编辑功能进行修改

可就在现在我发现一个很是郁闷的问题
FormView在编辑记录时,数据库中的记录并未做任何更改!

 <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" DataSourceID="_fv_source" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" >
                <EmptyDataTemplate>
                <asp:LinkButton Text="点击这里新建一个公告" CommandName="New" runat="server"></asp:LinkButton>
                </EmptyDataTemplate>

                <EditItemTemplate>
                    <table width="400" border="0" cellspacing="1" cellpadding="6">
                        <tr>
                            <td>
                                ID</td>
                            <td>
                                <%# Eval("id") %>
                               </td>
                        </tr>
                        <tr>
                            <td>
                                Announce</td>
                            <td>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Announce") %>' Height="189px" TextMode="MultiLine" Width="571px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox1"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="edit"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td>
                                开始时间</td>
                            <td>
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("datestart") %>'>
                                </asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="TextBox2"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="edit"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td>
                                结束时间</td>
                            <td>
                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dateend") %>'>
                                </asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="TextBox3"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="edit"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                                    Text="更新" ValidationGroup="edit"></asp:LinkButton>
                                <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" CommandName="Cancel"
                                    Text="取消" ValidationGroup="edit"></asp:LinkButton></td>
                        </tr>
                    </table>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <table width="400" border="0" cellspacing="1" cellpadding="6">
                        <tr>
                            <td>
                                Announce</td>
                            <td style="width: 493px">
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Announce") %>' Height="187px" TextMode="MultiLine" Width="509px"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="insert"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td>
                                开始时间</td>
                            <td style="width: 493px">
                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("datestart") %>'>
                                </asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="insert"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td>
                                结束时间</td>
                            <td style="width: 493px">
                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dateend") %>'>
                                </asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3"
                                    Display="Dynamic" ErrorMessage="*" ValidationGroup="insert"></asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Insert"
                                    Text="插入" ValidationGroup="insert"></asp:LinkButton>
                                <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" CommandName="Cancel"
                                    Text="取消" ValidationGroup="insert"></asp:LinkButton></td>
                        </tr>
                    </table>
                </InsertItemTemplate>
                <ItemTemplate>
                    <table width="400" border="0" cellspacing="1" cellpadding="6">
                        <tr>
                            <td>
                                ID</td>
                            <td>
                                <%# Eval("ID") %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Announce:</td>
                            <td>
                                <%# Eval("Announce") %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                开始时间</td>
                            <td>
                                <%# Eval("datestart") %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                结束时间</td>
                            <td>
                                <%# Eval("dateend") %>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:LinkButton ID="EditButton" runat="server" CausesValidation="True" CommandName="Edit"
                                    Text="编辑">
                                </asp:LinkButton>
                                <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="True" CommandName="Delete"
                                    Text="删除">
                                </asp:LinkButton>
                                <asp:LinkButton ID="NewButton" runat="server" CausesValidation="True" CommandName="New"
                                    Text="新建">
                                </asp:LinkButton></td>
                        </tr>
                    </table>
                </ItemTemplate>
                <FooterStyle BackColor="Tan" />
                <EditRowStyle BackColor="#EFEFEF" ForeColor="Black" />
                <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                <HeaderStyle BackColor="Tan" Font-Bold="True" />
            </asp:FormView>

SqlDataSource

 <asp:SqlDataSource ID="_fv_source" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnectionstrings %>"
                DeleteCommand="DELETE FROM [Announce] WHERE [ID] = @ID" InsertCommand="INSERT INTO [Announce] ([Announce], [datestart], [dateend], [publishdate]) VALUES (@Announce, @datestart, @dateend, @publishdate)"
                SelectCommand="SELECT * FROM [Announce] WHERE ([ID] = @ID)"
                UpdateCommand="UPDATE [Announce] SET [Announce] = @Announce, [datestart] = @datestart, [dateend] = @dateend WHERE [ID] = @ID" OnInserted="_fv_source_Inserted" OnInserting="_fv_source_Inserting" >
                <DeleteParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                </DeleteParameters>
                <UpdateParameters>
                    <asp:Parameter Name="Announce" Type="String" />
                    <asp:Parameter Name="datestart" Type="DateTime" />
                    <asp:Parameter Name="dateend" Type="DateTime" />

                    <asp:Parameter Name="ID" Type="Int32" />
                </UpdateParameters>
                <SelectParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                </SelectParameters>
                <InsertParameters>
                    <asp:Parameter Name="Announce" Type="String" />
                    <asp:Parameter Name="datestart" Type="DateTime" />
                    <asp:Parameter Name="dateend" Type="DateTime" />
                    <asp:Parameter Name="publishdate" Type="DateTime" />
                </InsertParameters>
            </asp:SqlDataSource>

没发现什么不对劲的啊
怎么会这样呢?

已找到原因:
禁用了ViewState,启用后就好了

静态文件的阅读计数器

2006年06月11日 2:58 下午  |  分类:Develop

在经典的编码区里看到很多关于此类的问题
基本上是用fso生成html文件以后,如何统计文章的点击数?
其实方法很简单
可以用<iframe>src到一个计数文件,如:count.asp?id=
也可以<script src=”"></script>这种方式
我比较喜欢用第二种
既然很多朋友还不了解
这里就给出一个方案吧
大家可以在此基础上进行扩展了
首先分析一下
count.asp这个文件
它有二个目的:
1、统计更新点击数
2、显示点击数
要注意的是
1、我们是以js方式调用的,所以在该.asp文件中,要以document.write才能显示值
2、传递文章的ID,至于ID如何传进来?fso了
如在模板中
<script src=”count.asp?id=$id$”></script>
将这里的$id$替换就行了
count.asp

&lt;%
dim id,count
id = Request.querystring("id")
if not isnumeric(id) then
   response.end
else
   id = clng(id)
end if
sql = "update ..... set hit = hit + 1 where id="&id
conn.execute(sql)  '更新统计数
count = conn.execute("select hit from .... where id="&id)(0)   '得到统计数
response.write "document.write('点击数:"&count&"')"
%&gt;

URL重写之实现IHttpHandler接口

2006年06月2日 5:08 下午  |  分类:Develop

以前用url重写时是用的ms urlrewriter,用了以后发现了很多不足,自定义功能太弱,而且随着重写规则的增加,web.config可能会越来越大,实际上,url重写就是实现IHttpHandler接口.
整个流程分二步走:
1、用一个xml文件来存储重写规则,其中这些规则是一些简单的正则表达式
2、实现IHttpHandler接口
首先看一下xml文件的格式:

<?xml version="1.0" encoding="utf-8" ?>
<root>
<regex>
<!--重写以后的虚拟地址-->
<b><![CDATA[xxx,(?<id>[0-9]+).html$]]></b>
<!--实际地址-->
<a><![CDATA[xxx.aspx?id=${id}]]></a>
</regex>
</root>

相信上面的xml大家都能看懂.

using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
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.Text;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;
//RegexInfo结构,用来存储从xml文件中读取到的数据
public struct RegexInfo
{
public string _before;
public string _after;
public RegexInfo(string before, string after)
{
_before = before.ToLower();
_after = after.ToLower();
}
}
//ipFilter结构,用来存储被封的IP
public struct ipFilter
{
public string _ip;
public ipFilter(string ip)
{
_ip = ip;
}
}
public class HtmlHttpHandler : IHttpHandler   //实现IHttpHandler接口
{

private List<RegexInfo> _regex_list = new List<RegexInfo>();
private List<ipFilter> _ip_filter = new List<ipFilter>();
public HtmlHttpHandler()
{
DataSet ds = new DataSet();
//读取url重写规则文件,并写入RegexInfo结构的实例中
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Regexs.xml"));
foreach (DataRow r in ds.Tables["regex"].Rows)
_regex_list.Add(new RegexInfo(((string)r["b"]).Trim(), ((string)r["a"]).Trim()));
ds.Reset();
//读取被封的IP列表
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ipFilter.xml"));
foreach(DataRow r in ds.Tables["IpFilters"].Rows)
_ip_filter.Add(new ipFilter((string)r["ip"]));
}

public void ProcessRequest(HttpContext context)
{
string _ip = context.Request.UserHostAddress;   //获取IP
foreach (ipFilter r in _ip_filter)
{
if (_ip == r._ip)
{
context.Response.Write("对不起,您的IP:"+_ip+"已被限制!");
context.Response.End();
}
}
string path = context.Request.Path.ToLower();   //获取当前访问的重写过的虚假URL
foreach (RegexInfo r in _regex_list)
path = Regex.Replace(path, r._before, r._after);      //匹配出其真实的URL
context.Server.Execute(path);
}

// Override the IsReusable property.
public bool IsReusable
{
get { return true; }
}
}

OK,IHttpHandler接口就被实现了,下面稍配一下web.config就可以实现URL重写了
在web.config的<system.web></system.web>中加入

<httpHandlers>
<add verb=”*” path=”*.html” type=”HtmlHttpHandler”/>
</httpHandlers>

表示后缀名为.html的文件全部交给HtmlhttpHandler类去处理
最后配一下iis就行了
本blog的url重写就是这样实现的,至于简繁的转换,你可以加到ProcessRequest中,至于如何实现转换,到这个blog上找找吧:)

Pages: « 1 2 3 ...106 107 108 109 110 111 112 113 »