分类: C# and .NET

  • 在带有 Validator 对象的页面进行 Response.Redirect 转向

    由于客户端 Validation 触发在 Button 的事件之前,所以如果在事件里定义转向的话,会被 Validator 们阻止。
    其实解决办法也很简单,将 Button 的 CausesValidation 属性设置为 false 即可。
    我的想法是,由服务器端生成的操作,都有相应的属性可以对其进行控制。呃,仅仅是想法。

    For a detailed English version of this article, please visit:
    http://dengkefu.com/boke/programming/c-sharp-and-dot-net/redirection-in-a-page-with-validation-objects.html

  • Redirection in a Page with Validation Objects

    I’ve been up to a new C# with ASP.NET project lately, and I plan to record down the problems occurred along the development, of course, with solutions.

    Here is the first one, about Redirection and Validation. It’s pretty simple, or, I should say amateur. You got it, amateur is who I am. ^^

    I encountered this problem that, Okay, here comes the

    Problem Description

    I’ve got a Button object with OnClick Event in page1, which, when clicked, Response.Redirect to page2. Meanwhile, I have some Validator objects in page1, too. The thing is, the client-side Validation occurs before even reaching the Event for the Button. That is to say, the Validators prevent Redirection from happening.

    Solution

    You’ll love this because it’s so easy. In the Button’s properties list, find "CausesValidation" and set it to false. That’s it.

    My thought is, there’s always some property control if an operation is generated on the server-side.

  • Displaying DateTime Object as Desired

    DateTime is a common type we deal with frequently in the development of C#-ASP.NET project. As a result, how to display a DateTime object properly is the knowledge we have to know as a web service developer.

    In the following paragraphs, I made a summary of formatting DateTime object in several circumstances to get it displayed as needed:

    • Format DateTime string retrieved from database and to be binded to Data Controls.
      <ASP:BoundColumn DataField="JoinTime" DataFormatString="{0:yyyy-MM-dd}" >
      </ASP:BoundColumn>
      <ASP:BoundColumn DataField="CheckoutTime" DataFormatString="{0:yyyy-MM-dd HH24:mm:ss}">
      </asp:BoundColumn>

    • Statement in the CodeFile to get a DateTime string.
      e.Item.Cell[0].Text = Convert.ToDateTime(e.Item.Cell[0].Text).ToShortDateString();

    • With the help of String class.
      String.Format( "yyyy-MM-dd ", theDateTimeObj);

    • With the help of Convert method.
      Convert.ToDateTime("2008-12-09").ToString;
      Convert.ToDateTime(dr["PubDate"]).ToShortDateString();

    • ToString method of DateTime class.
      DateTime.Now.ToString("yyyyMMddhhmmss");
      DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");

    • Show only year and month.
      DataBinder.Eval(Container.DataItem,"starttime","{0:yyyy-MM}");

    Certainly, there are more situations when you have to format a DateTime object, and the rules could be deduced from above.

    Technorati Tags: ,,
  • Remove Duplicate Records in a DataTable the Easy Way

    The Merge method of DataTable class is convenient for combining two tables into one. However, the result table may contain duplicate data after the operation. We could write our own function to remove the duplicates, or, we could take advantage of a built-in method of DataView class.

    Method Intro

    There is this DataView method called ToTable with two parameters: (and a three-parameter overloaded version)

    a boolean param distinct
    If true, the returned System.Data.DataTable contains rows that have distinct values for all its columns. The default value is false.

    a string array param columnNames
    A string array that contains a list of the column names to be included in the returned System.Data.DataTable. The System.Data.DataTable contains the specified columns in the order they appear within this array.

    Thought

    We could first create a DataView object dv using the source table dt, then we turn dv into the destination "slim" DataTable dt through that ToTable method introduced above. The redundant data will be removed automatically.

    Coding

    Let’s assume dt is the source DataTable object with duplicate records.

    // create a dv from the source dt
    DataView dv = new DataView(dt);
    // set the output columns array of the destination dt
    string[] strColumns = {"NodeID", "Title", "Url"};
    // true = yes, i need distinct values.
    dt = dv.ToTable(true, strColumns);

    That’s it, the easy way to get redundant data removed from a DataTable object.

    Technorati Tags: ,,
  • Dynamic Tree Construction according to User Role and Page

    In the developing environment of C# and .NET, dynamic data binding isn’t anything new at all. I’m here just to make a summary of how to do the job to a TreeView object, and add a few contents depending on my practical experience.

    Keywords: dynamic tree construction, user role, page.

    Problem Description

    In the classic three-layer architecture adopted by my project, we have

    1. data tables that are dealt with by a DAL-located class database.cs;

    2. a series of corresponding BLL classes to manipulate data retrieved from those tables;

    3. aspx pages and aspx.cs code files in the presentation layer.

    which means following elements are involved:

    1. data table User, UserRole, RoleTree;

    2. class User.cs, UserRole.cs, RoleTree.cs;

    3. example page sampleTree.aspx and its code file sampleTree.aspx.cs.

    A picture speaks more than a thousand words. Let’s first take a look at the chart below to get an overview of how this work is going to be done.

    Solution Pt1: User Login

    By the input username and password, we first get the userId, through which user role(s) are obtained and stored in a Session object. In case of more than one role for a specific user, we take an ArrayList as the role container.

    if (Page.IsValid)
    {
        User usr = new User();
        string userId = "";
        SqlDataReader recs = usr.GetUserLogin(txtUserName.Text.Trim(), txtPassword.Text.Trim());

        if (recs.Read())
        {
            userId = recs["UserID"].ToString();
        }
        recs.Close();

        if ((userId != String.Empty) && (userId != ""))
        {
            // get user roles, put them into session
            ArrayList alRoleIDs = new ArrayList();
            UserRole ur = new UserRole();
            SqlDataReader dr = ur.GetRoleByUserID(Int32.Parse(userId));
            while (dr.Read())
            {
                alRoleIDs.Add(Int32.Parse(dr["RoleID"].ToString()));
            }
            Session.Add("RoleIDs", alRoleIDs);
            dr.Close();
        }

    Solution Pt2: Tree Construction

    Then we take the RoleIDs of ArralyList above and some PageID of int as arguments to get the tree. Codes below are sample codes from sampleTree.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindTreeData(treeSidebar, (ArrayList)Session["RoleIDs"]);
        }
    }

    private void BindTreeData(TreeView tv, ArrayList al)
    {
        RoleTree rt = new RoleTree();
        // when applied to different pages, take RoleIDs of ArrayList and PageID of int as arguments
        DataTable dt = rt.GetTreeByRoleIDandPageID(al, 3); // 3 is an exmaple of pageId
        tv.Nodes.Clear();

        foreach (DataRow row in dt.Select())
        {
            TreeNode tempNode = new TreeNode();
            tempNode.Text = row["Title"].ToString();
            tempNode.Value = row["NodeID"].ToString();
            tempNode.Expanded = false;
            tempNode.NavigateUrl = row["Url"].ToString();

            tv.Nodes.Add(tempNode);
        }
    }

    Further Notice

    //It is especially useful when applied to MasterPages.

    //This solution does not take node’s parent into account, which means the TreeView object constructed is not a real tree, strictly speaking.

  • DataFormatString in GridView

    I’ve been working on an ASP.NET project lately, which means it’s high time I write something down to build up my own knowledge base and track down my trail of learning how to code effectively. Hence this article, just another ASP.NET record.

    (更多…)