一.设计从gridview获取ID和NAME
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace WebControlLibrary
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:GetIDAndName runat=server></{0}:GetIDAndName>")]
public class GetIDAndName : CompositeControl //WebControl //, IPostBackEventHandler, IPostBackDataHandler
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("http://blog.youkuaiyun.com/zhanghefu/")]
[Localizable(true)]
[Description("The address of URL to open by the Button.")]
public string URL
{
get
{
String s = (String)ViewState["URL"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["URL"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("0")]
[Localizable(true)]
[Description("To set the WindowWidth of URL which is opened by the Button.")]
public int WindowWidth
{
get
{
object o = ViewState["WindowWidth"];
if (o != null)
{
return int.Parse(ViewState["WindowWidth"].ToString());
}
else
{
return 0;
}
}
set
{
ViewState["WindowWidth"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("0")]
[Localizable(true)]
[Description("To set the WindowHeight of URL which is opened by the Button.")]
public int WindowHeight
{
get
{
object o = ViewState["WindowHeight"];
if (o != null)
{
return int.Parse(ViewState["WindowHeight"].ToString());
}
else
{
return 0;
}
}
set
{
ViewState["WindowHeight"] = value;
}
}
public TextBox TextBox;
public TextBox TextBox2;
//public HiddenField HiddenField;
public Button Button;
protected override void CreateChildControls()
{
TextBox = new TextBox();
TextBox2 = new TextBox();
//HiddenField = new HiddenField();
Button = new Button();
TextBox.ID = "txtName";
this.Controls.Add(TextBox);
TextBox2.ID = "txtID";
this.Controls.Add(TextBox2);
//HiddenField.ID = "hfID";
//HiddenField.Visible = true;
//this.Controls.Add(HiddenField);
Button.ID = "btnChoose";
Button.Text = "选择";
Button.Click += new EventHandler(Button_Click);
this.Controls.Add(Button);
}
public event GetNameAndIDEventHandler OpenDilog;
protected void Button_Click(object sender, EventArgs e)
{
try
{
if (URL == "" || URL ==null)
{
string strRemind = "The URL is not null.please input your URL!";
this.Page.RegisterStartupScript(System.Guid.NewGuid().ToString(),"<script>window.alert('" + strRemind + "')</script>");
}
//else
//{
// OpenDilog(this, new SuzsoftArgs(this.Page, URL, WindowWidth, WindowHeight));
//}
if (OpenDilog != null)
{
OpenDilog(this, new SuzsoftArgs(this.Page, URL, WindowWidth, WindowHeight));
}
}
catch (Exception ex)
{
return;
}
}
//定义委托
public delegate void GetNameAndIDEventHandler(object send, SuzsoftArgs e);
public class SuzsoftArgs : EventArgs
{
private string strUrl = "";
public string StrUrl
{
get { return strUrl; }
set { strUrl = value; }
}
private string strNmae = "";
public string StrName
{
get { return strNmae; }
set { strNmae = value; }
}
private string strID = "";
public string StrID
{
get { return strID; }
set { strID = value; }
}
private int intWidth;
public int IntWidth
{
get
{
return intWidth;
}
set
{
if (this.intWidth != value)
this.intWidth = value;
}
}
private int intHeight;
public int IntHeight
{
get
{
return intHeight;
}
set
{
if (this.intHeight != value)
this.intHeight = value;
}
}
public static string BaseUrl
{
get
{
string strBaseUrl = "";
strBaseUrl += "http://" + HttpContext.Current.Request.Url.Host;
if (HttpContext.Current.Request.Url.Port.ToString() != "80")
{
strBaseUrl += ":" + HttpContext.Current.Request.Url.Port;
}
strBaseUrl += HttpContext.Current.Request.ApplicationPath;
return strBaseUrl + "/";
}
}
public SuzsoftArgs(System.Web.UI.Page pageCurrent, string strUrl, int intWidth, int intHeight)
{
string strScript = "";
strScript += "var strFeatures = 'width:" + intWidth.ToString() + "px;height:" + intHeight.ToString() + "px';";
strScript += "var strName ='__WIN';";
if (strUrl.Substring(0, 1) == "/")
{
strUrl = strUrl.Substring(1, strUrl.Length - 1);
}
strUrl = BaseUrl + strUrl;
strScript += "window.open(/"" + strUrl + "/",strName,strFeatures);";
pageCurrent.ClientScript.RegisterStartupScript(this.GetType(), System.Guid.NewGuid().ToString(),
"<script language='javascript'>" + strScript + "</script>");
}
}
}
}
////呈现控件时初始数据
//protected override void OnPreRender(EventArgs e)
//{
// TextBox.Text = "";
// TextBox2.ID = "";
// //HiddenField.Value = "";
// //Button.Click += new EventHandler(Button_Click);
//}
二.GridView.aspx.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
<%@ Register Assembly="Suzsoft.Web" Namespace="Suzsoft.Web.UI.WebControls" TagPrefix="asp" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 514px">
<asp:SGridView ID="gvwSearch" runat="server" AllowCascade="True" AllowPaging="True"
AllowScrollBars="False" AllowSorting="True" ArrowColor="Gray" AutoGenerateColumns="False"
BorderCollapse="True" DarkshadowColor="White" DataSourceID="SqlDataSource2" DivBorderColor=""
DivBorderStyle="NotSet" DivBorderWidth="" DownImageURL="" ExtendedPagerStyle="Common"
ExtendedStyle="NotSet" FaceColor="White" GridLines="Horizontal" HighlightColor="LightGray"
OnSorting="gvwSearch_Sorting" ScrollBarsCss="" ShadowColor="LightGray" ShowActionToolBar="False"
SubGridViewTemplateID="" ThreeDlightColor="White" TrackColor="White" UpImageURL=""
UseStyleForSubGrid="False" Width="100%" XScrollBar="auto" YScrollBar="auto" DataKeyNames="id"
OnRowDataBound="gvwSearch_RowDataBound" OnPageIndexChanging="gvwSearch_PageIndexChanging">
<Columns>
<%-- sp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id" />
--%>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="labID" Text='<%# DataBinder.Eval(Container, "DataItem.id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="姓名" ControlStyle-CssClass="grilviewLink" SortExpression="first_name">
<ItemTemplate>
<asp:LinkButton ID="btnReturn" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.last_name").ToString() + " " + DataBinder.Eval(Container, "DataItem.first_name").ToString()%>'> </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="title" HeaderText="title" SortExpression="title" />
<asp:BoundField DataField="assigned_user_id" HeaderText="assigned_user_id" SortExpression="assigned_user_id" />
</Columns>
<PagerSettings Position="TopAndBottom" />
<HeaderStyle Wrap="True" />
</asp:SGridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CRMConnectionString %>"
SelectCommand="SELECT [id], [first_name], [last_name], [title], [assigned_user_id] FROM [contacts]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td style="width: 514px">
</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
//关闭窗口
function OnCancel()
{
window.returnValue = null;
window.close();
}
//返回用户名字
function onReturnFirstName(id,FirstName)
{
window.returnValue = id + "^" + FirstName;
window.close();
}
</script>
</div>
</form>
</body>
</html>
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
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region 排序
/// <summary>
/// 排序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// Author:kate.zhang Date:2007.1.10
/// Modifier:
/// </remarks>
protected void gvwSearch_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtContacts = gvwSearch.DataSource as DataTable;
if (dtContacts != null)
{
DataView dvContacts = new DataView(dtContacts);
dvContacts.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gvwSearch.DataSource = dvContacts;
gvwSearch.DataBind();
}
}
#endregion
#region 分页
/// <summary>
/// 分页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// Author:kate.zhang Date:2007.1.10
/// Modifier:
/// </remarks>
protected void gvwSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwSearch.PageIndex = e.NewPageIndex;
gvwSearch.DataBind();
}
#endregion
#region 改变排序方向
/// <summary>
/// 改变排序方向
/// </summary>
/// <param name="sortDireciton">排序方向</param>
/// <returns>改变后的排序方向</returns>
/// <remarks>
/// Author:kate.zhang Date:2007.1.10
/// </remarks>
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string strSortDirection = String.Empty;
switch (sortDireciton)
{
case SortDirection.Ascending:
strSortDirection = "ASC";
break;
case SortDirection.Descending:
strSortDirection = "DESC";
break;
}
return strSortDirection;
}
#endregion
#region 初始化gridview
/// <summary>
/// 初始化grilview
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author:kate.zhang Date:2007.1.10
/// Modifier:
/// </remarks>
protected void gvwSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton objBtn = e.Row.Cells[0].FindControl("btnReturn") as LinkButton;
Label objID = e.Row.Cells[0].FindControl("labID") as Label;
objBtn.Attributes.Add("onclick", "onReturnFirstName('" + objBtn.Text.Split(' ')[0] + "','"+objID.Text+"')");
}
else
{
UIHelper.Alert(this.Page, "信息传输发生异常,请检查!");
}
}
}
#endregion
}
三.测试网页Default.aspx.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="WebControlLibrary" Namespace="WebControlLibrary" TagPrefix="cc1" %>
<!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>Untitled Page</title>
<script type="text/javascript">
function OpenSearchDialog(strReqPathId,strID,strName)
{
var strFeatures = "dialogWidth=590px;dialogHeight=520px;center=yes;help=no;status=no";
var strReturnMessage=window.showModalDialog(strReqPathId,"",strFeatures);
if(strReturnMessage==null || strReturnMessage=="")
{
//do nothing
}
else
{
var strValues = strReturnMessage.split('^');
document.getElementById(strID).value = strValues[0];
document.getElementById(strName).value = strValues[1];
}
}
//btnChooseUser.Attributes.Add("onclick", "OpenSearchDialog('" + base.BaseUrl + "DialogFrame.aspx?URL=Modules/SearchUsers.aspx','"+txtAssignedUserName.ClientID+ "')");
//btnPerson.Attributes.Add("onclick", "OpenPersonModalDialog('" + base.BaseUrl + "System/DialogFrame.aspx?URL=modules/PersonnelSelector.aspx?SelMode=" + strParam + "','" + txtPersonName.ClientID + "','" + hfPersonID.ClientID + "','" + hfWorkNo.ClientID + "')");
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:GetIDAndName ID="GetIDAndName1" runat="server" Style="z-index: 100; left: 0px;
position: absolute; top: 0px" WindowHeight="300" WindowWidth="300" OnOpenDilog="GetIDAndName1_OpenDilog" URL="" />
</div>
</form>
</body>
</html>
<%--protected void gvwAlternateKey_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton objBtn = e.Row.Cells[0].FindControl("btnReturn") as LinkButton;
objBtn.Attributes.Add("onclick","onReturn('" + objBtn.Text + "')");
HyperLink objHyp = e.Row.Cells[1].Controls[0] as HyperLink;
objHyp.Attributes.Add("onclick", "onReturn('" + objBtn.Text + "')");
}
}--%>
<%-- <script language="javascript" type="text/javascript">
function onReturn(alternateKey)
{
window.returnValue = alternateKey;
window.close();
}
</script>--%>
<%--<asp:gridview width="100%" id="gvwAlternateKey" runat="server" autogeneratecolumns="False"
datasourceid="odsAlternateKey" onrowdatabound="gvwAlternateKey_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="AlternateKey">
<ItemTemplate>
<asp:LinkButton runat="server" ID="btnReturn" Text='<%#Eval("PRODUCTCATEGORYALTERNATEKEY") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataTextField="PRODUCTCATEGORYALTERNATEKEY" NavigateUrl="#" HeaderText="AlternateKey" />
</Columns>
</asp:gridview>--%>
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void GetIDAndName1_OpenDilog(object send, WebControlLibrary.GetIDAndName.SuzsoftArgs e)
{
e.IntHeight = 300;
e.IntWidth = 300;
GetIDAndName1.Attributes.Add("onclick", "OpenSearchDialog('" + "GridView.aspx" + "','"+GetIDAndName1.TextBox2.ClientID+"','"+GetIDAndName1.TextBox.ClientID+"')");
}
protected void Page_Load(object sender, EventArgs e)
{
GetIDAndName1.URL = "GridView.aspx";
}
}