C#技巧

 1. 获取GridView的主键值:

    public static T GetKey(this GridView grid, int rowIndex)
{  
    T key = (T)grid.DataKeys[rowIndex].Value;
    return key;
}

示例:

protected void gvMaster_RowEditing(object sender, GridViewEditEventArgs e) { string key = gvMaster.GetKey(e.NewEditIndex); }  

  2. 获取GridView的行号:

public static int GetRowIndex(this GridViewCommandEventArgs e) { GridViewRow gvrow = (GridViewRow)(((Control)e.CommandSource).NamingContainer); return gvrow.RowIndex; }

示例:

protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e) { int rowIndex = e.GetRowIndex(); }  

    3. 查找指定ID的控件,并转换成指定类型:
public static T FindControl(this Control control, string id) where T : class { Control c = control.FindControl(id); return (c as T); } 示例:

//从整个页面里查找ID为lblTest的Label this.FindControl("lblTest"); //从Panel里查找ID为lblTest的Label Panel1.FindControl("lblTest");

  4. 查找指定类型的控件:

public static List FindControls(this Control control) where T : Control { Action> findhelper =null; findhelper= (ctl, list) => { if (ctl is T) { list.Add((T)ctl); } if (ctl.HasControls()) { foreach (Control c in ctl.Controls) { findhelper(c, list); } } }; List controls =new List(); findhelper(control, controls); return controls; }

示例:

//从整个页面里查找所有Label this.FindControls(); //从Panel里查找所有Label Panel1.FindControls()

备注:
  在实际开发中有个不错的应用场景——找到所有的RequiredFieldValidator控件并统一设置其错误信息和提示信息:

var rs = this.FindControls(); foreach (var r in rs) { r.ErrorMessage = "*"; r.ToolTip = "不能为空"; }

  当然,如果在FindControls中增加一个Action 参数应该是个不错的方案,这样以上语句就可以直接写成:

var rs = this.FindControls(r => { r.ErrorMessage = "*"; r.ToolTip = "不能为空"; });

  5. 判断本页是是否使用Ajax (其实就是判断是否使用了ScriptManager):

public static bool IsAjaxPage(this Page page) { return (ScriptManager.GetCurrent(page) != null); } public static bool IsAjaxPage(this Control control) { return (ScriptManager.GetCurrent(control.Page) != null); }

示例:

if (this.IsAjaxPage()) { do sth about ajax }

6. UpdatePanel 调用javascript 显示信息:

public static void Alert(this UpdatePanel panel, string message) { if (message.Length > 50) { message = message.Substring(0, 50);//最多显示50个字符 } //去除javascript不支持的字符 message = Utility.ReplaceStrToScript(message);       ScriptManager.RegisterClientScriptBlock(panel, panel.GetType(), "Message", string.Format( " alert('{0}'); ", message) , true); }

示例:

udpHeader.Alert("Hello,I'm Bruce!");//注:udpHeader 是UpdatePanel 类型

 

把 alert 换成漂亮的提示框就perfect了。

 

原文出处:http://dotnet.cnblogs.com/page/49342/

你可能感兴趣的:(C#技巧)