說明:想讓GridView的某欄合併儲存格(非動態等資料繫結後,再判斷資料是否相符),該怎麼做?
做法:
在GridView的PreRender(GridView載入後與render前)事件中加上:
foreach (GridViewRow gvRow in GridView1.Rows)
{
if (gvRow.RowIndex > 0)//DataRow
{
//let column index+1 merge cell and assign the rows to across
GridView1.Rows[0].Cells[index].RowSpan = GridView1.Rows.Count;
//hide the extra cells
gvRow.Cells[index].Visible = false;
}
}
參考資料:
http://www.dotblogs.com.tw/mis2000lab/archive/2008/04/archive/2008/04/archive/2008/04/24/3452.aspx
http://pramaire.pixnet.net/blog/post/31837470-gridview%E8%B3%87%E6%96%99%E5%88%97row%E5%90%88%E4%BD%B5%E6%AC%84%E4%BD%8D
2014年12月31日 星期三
2014年7月30日 星期三
[ASP.NET] GridView樣板內控制項文字設定斷行
說明:因GridView內控制項(label)文字太長,想設定斷行。
作法:
1. 在GridView的RowDataBound事件內,找到該控制項。
2. 再設定特定長度或字元斷行,例:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblTest = (Label)e.Row.FindControl("lblTest");
if (lblTest .Text.Length > 0)
{
//1. 直接insert <br/>
blTest.Text = (lblTestt.Text.IndexOf('.') > 0) ? lblTest.Text.Insert(lblTestt.Text.IndexOf('.') + 1, "<br/>") : blTest.Text;
// 2. 用replace加入<br/>
lblTest.Text = lblTest.Text.Replace(".", ".<br/>");
}
}
}
參考資料:
http://www.dreamincode.net/forums/topic/117242-wrapping-around-a-symbol/
http://msdn.microsoft.com/zh-tw/library/11w09h50(v=vs.110).aspx
作法:
1. 在GridView的RowDataBound事件內,找到該控制項。
2. 再設定特定長度或字元斷行,例:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblTest = (Label)e.Row.FindControl("lblTest");
if (lblTest .Text.Length > 0)
{
//1. 直接insert <br/>
blTest.Text = (lblTestt.Text.IndexOf('.') > 0) ? lblTest.Text.Insert(lblTestt.Text.IndexOf('.') + 1, "<br/>") : blTest.Text;
// 2. 用replace加入<br/>
lblTest.Text = lblTest.Text.Replace(".", ".<br/>");
}
}
}
參考資料:
http://www.dreamincode.net/forums/topic/117242-wrapping-around-a-symbol/
http://msdn.microsoft.com/zh-tw/library/11w09h50(v=vs.110).aspx
2014年5月30日 星期五
[ASP.NET] a potentially dangerous request.form value was detected from the client
說明:ASP.NET 4.0,另開新視窗時,出現錯誤訊息:a potentially dangerous request.form value was detected from the client,是避免XSS (Cross-site scripting)攻擊(一種夾帶script語法到網頁的方式)的訊息,所以偵測到post <或>字元,就會出現此訊息。
解決方法:
1.在web.config的<system.web></system.web>標籤中加上 <httpRuntime requestValidationMode="2.0" />與<pages validateRequest="false" />,因為ASP.NET 2.0 request validation的順序會在request processing events之後,若限個別pages,可在各pages加上<@ Page validateRequest="false" %>,但此方法不推薦。
2. 使用HttpUtility.HtmlEncode (Server.HtmlEncode)或AntiXss.HtmlEncode (import AntiXssLibrary.dll),會將特殊字元編碼HTML字元集,如<換為<,"換為",供HTML正常輸出。
參考資料:
http://stackoverflow.com/questions/81991/a-potentially-dangerous-request-form-value-was-detected-from-the-client
http://www.asp.net/whitepapers/aspnet4/breaking-changes
http://msdn.microsoft.com/en-us/library/hh882339.aspx
http://msdn.microsoft.com/en-us/library/aa973813.aspx
http://msdn.microsoft.com/en-us/library/ms998274.aspx
http://www.dotblogs.com.tw/johnny/archive/2010/03/01/13829.aspx
http://www.dotblogs.com.tw/coca/archive/2011/03/11/21794.aspx
http://blog.darkthread.net/post-2008-06-18-eval-xss.aspx
解決方法:
1.在web.config的<system.web></system.web>標籤中加上 <httpRuntime requestValidationMode="2.0" />與<pages validateRequest="false" />,因為ASP.NET 2.0 request validation的順序會在request processing events之後,若限個別pages,可在各pages加上<@ Page validateRequest="false" %>,但此方法不推薦。
2. 使用HttpUtility.HtmlEncode (Server.HtmlEncode)或AntiXss.HtmlEncode (import AntiXssLibrary.dll),會將特殊字元編碼HTML字元集,如<換為<,"換為",供HTML正常輸出。
參考資料:
http://stackoverflow.com/questions/81991/a-potentially-dangerous-request-form-value-was-detected-from-the-client
http://www.asp.net/whitepapers/aspnet4/breaking-changes
http://msdn.microsoft.com/en-us/library/hh882339.aspx
http://msdn.microsoft.com/en-us/library/aa973813.aspx
http://msdn.microsoft.com/en-us/library/ms998274.aspx
http://www.dotblogs.com.tw/johnny/archive/2010/03/01/13829.aspx
http://www.dotblogs.com.tw/coca/archive/2011/03/11/21794.aspx
http://blog.darkthread.net/post-2008-06-18-eval-xss.aspx
2014年4月20日 星期日
[ASP.NET] 在Server端動態加入Client script
說明:想在server端建立client script時,該怎麼做?
作法:
使用Page.ClientScript屬性取得的ClientScriptManager object提供的四個method:
1. RegisterStartupScript(Type type, string key, string script, bool addScriptTags):
在網頁載入完成後及網頁OnLoad事件觸發前,會執行所加入的script,適用非一開始會用
到的script。
2. RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags):
會將script加入至網頁頂端(<form>下),不保證script可依註冊的順序輸出。
3. RegisterClientScriptInclude(Type type, string key, string url):
動態加入js 檔的script,在以動態方式加入其他script前就會加入該script,因此可能無法參
考網頁上的某些項目。
4. RegisterOnSubmitStatement(Type type, string key, string script):
加入可回應網頁onsubmit 事件的script (ex: confirm),在送出網頁前即執行script,因此可取消送出動作。例:
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", "return confirm('Do you want to submit the page?')");
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.page.clientscript%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/system.web.ui.clientscriptmanager%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms178207%28v=vs.100%29.aspx
http://www.dotblogs.com.tw/hatelove/archive/2009/10/28/11325.aspx
http://msdn.microsoft.com/zh-tw/library/7ytf5t7k%28v=vs.100%29.aspx
作法:
使用Page.ClientScript屬性取得的ClientScriptManager object提供的四個method:
1. RegisterStartupScript(Type type, string key, string script, bool addScriptTags):
在網頁載入完成後及網頁OnLoad事件觸發前,會執行所加入的script,適用非一開始會用
到的script。
2. RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags):
會將script加入至網頁頂端(<form>下),不保證script可依註冊的順序輸出。
3. RegisterClientScriptInclude(Type type, string key, string url):
動態加入js 檔的script,在以動態方式加入其他script前就會加入該script,因此可能無法參
考網頁上的某些項目。
4. RegisterOnSubmitStatement(Type type, string key, string script):
加入可回應網頁onsubmit 事件的script (ex: confirm),在送出網頁前即執行script,因此可取消送出動作。例:
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", "return confirm('Do you want to submit the page?')");
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.page.clientscript%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/system.web.ui.clientscriptmanager%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms178207%28v=vs.100%29.aspx
http://www.dotblogs.com.tw/hatelove/archive/2009/10/28/11325.aspx
http://msdn.microsoft.com/zh-tw/library/7ytf5t7k%28v=vs.100%29.aspx
2014年3月27日 星期四
[ASP.NET] 套用MasterPage的Button權限控管
說明:有使用MasterPage,想根據用戶的權限代號(Authority)管控頁面上的新增/編輯/刪除等button,無權限則disable該button。
做法:在MasterPage的PreRender事件中使用ContentPlaceHolder控制項的findcontrol找到新增/編輯/刪除等button後,再分別disable該button。例:
//namespace
[Flags]
public enum Privilege
{
None=0,
View=1,
Add=2,
Edit=4,
Remove=8,
All = None|View|Add|Edit|Remove
}
//xxx.master.cs
protected override void OnPreRender(EventArgs e)
{
try
{
Button btnAdd = (Button)ContentPlaceHolder1.FindControl("btnAdd");
Button btnEdit = (Button)ContentPlaceHolder1.FindControl("btnEdit");
Button btnDel = (Button)ContentPlaceHolder1.FindControl("btnDel");
if (Authority == (int)Privilege.View)
{
btnAdd.Disable = false;
btnEdit.Disable = false;
btnDel.Disable = false;
}
else if (Authority == (int)(Privilege.View | Privilege.Add))
{
btnEdit.Disable = false;
btnDel.Disable = false;
}
...以此類推
}
catch (Exception ex)
{
throw ex;
}
base.OnPreRender(e);
}
參考資料:
做法:在MasterPage的PreRender事件中使用ContentPlaceHolder控制項的findcontrol找到新增/編輯/刪除等button後,再分別disable該button。例:
//namespace
[Flags]
public enum Privilege
{
None=0,
View=1,
Add=2,
Edit=4,
Remove=8,
All = None|View|Add|Edit|Remove
}
//xxx.master.cs
protected override void OnPreRender(EventArgs e)
{
try
{
Button btnAdd = (Button)ContentPlaceHolder1.FindControl("btnAdd");
Button btnEdit = (Button)ContentPlaceHolder1.FindControl("btnEdit");
Button btnDel = (Button)ContentPlaceHolder1.FindControl("btnDel");
if (Authority == (int)Privilege.View)
{
btnAdd.Disable = false;
btnEdit.Disable = false;
btnDel.Disable = false;
}
else if (Authority == (int)(Privilege.View | Privilege.Add))
{
btnEdit.Disable = false;
btnDel.Disable = false;
}
...以此類推
}
catch (Exception ex)
{
throw ex;
}
base.OnPreRender(e);
}
參考資料:
2014年3月7日 星期五
[ASP.NET] 動態產生控制項TextBox、CalendarExtender與DropDownList並取值
說明:動態產生控制項TextBox、CalendarExtender與DropDownList並取值,其中產生控制項最好放在事件OnInit裡,可透過ViewState來更新控制項的屬性值。本例已有一列靜態控制項,並搭配HiddenField來紀錄資料列數。
語法:
//code behind
using AjaxControlToolkit;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
AddRecord(iNum, false);
}
}
protected void btnMore_Click(object sender, EventArgs e)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
iNum++;
hidNum.Value = iNum.ToString();
AddRecord(int.Parse(hidInvoiceNum.Value), true);
}
private void AddRecord(int iNum, bool blFlag)
{
int iTemp = 1;
if (blFlag) iTemp = iNum;
for (int i=iTemp; i <= iNum; i++)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TextBox txtNo = new TextBox();
txt.ID = "txtNo" + i;
tc1.Controls.Add(txtNo);
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
TextBox txtDate = new TextBox();
CalendarExtender ce = new CalendarExtender();
txtDate.ID = "txtDate" + i;
ce.TargetControlID = "txtDate" + i;
ce.Format = "yyyy/MM/dd";
this.PlaceHolder1.Controls.Add(ce);
tc2.Controls.Add(txtDate);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
DropDownList ddlType = new DropDownList();
ddlType.ID = "ddlType" + i;
ddlType.DataSource = datasource;
ddlType.DataTextField = "Text";
ddlType.DataValueField = "Value";
ddlType.DataBind();
tc3.Controls.Add(ddlType);
tr.Cells.Add(tc3);
//Add Server Control Table
this.tbTest.Rows.Add(tr);
}
//取值
for (int i = 0; i <= int.Parse(hidNum.Value); i++)
{
txtNo = (TextBox)tbTest.FindControl("txtNo" + i);
txtDate = (TextBox)tbTest.FindControl("txtDate" + i);
ddlType = (DropDownList)tbTest.FindControl("ddlType" + i);
}
語法:
//code behind
using AjaxControlToolkit;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
AddRecord(iNum, false);
}
}
protected void btnMore_Click(object sender, EventArgs e)
{
int iNum = 0;
if (!string.IsNullOrEmpty(hidNum.Value))
iNum = int.Parse(hidNum.Value);
iNum++;
hidNum.Value = iNum.ToString();
AddRecord(int.Parse(hidInvoiceNum.Value), true);
}
private void AddRecord(int iNum, bool blFlag)
{
int iTemp = 1;
if (blFlag) iTemp = iNum;
for (int i=iTemp; i <= iNum; i++)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TextBox txtNo = new TextBox();
txt.ID = "txtNo" + i;
tc1.Controls.Add(txtNo);
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
TextBox txtDate = new TextBox();
CalendarExtender ce = new CalendarExtender();
txtDate.ID = "txtDate" + i;
ce.TargetControlID = "txtDate" + i;
ce.Format = "yyyy/MM/dd";
this.PlaceHolder1.Controls.Add(ce);
tc2.Controls.Add(txtDate);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
DropDownList ddlType = new DropDownList();
ddlType.ID = "ddlType" + i;
ddlType.DataSource = datasource;
ddlType.DataTextField = "Text";
ddlType.DataValueField = "Value";
ddlType.DataBind();
tc3.Controls.Add(ddlType);
tr.Cells.Add(tc3);
//Add Server Control Table
this.tbTest.Rows.Add(tr);
}
//取值
for (int i = 0; i <= int.Parse(hidNum.Value); i++)
{
txtNo = (TextBox)tbTest.FindControl("txtNo" + i);
txtDate = (TextBox)tbTest.FindControl("txtDate" + i);
ddlType = (DropDownList)tbTest.FindControl("ddlType" + i);
}
[ASP.NET] 控制項tooltip與html title屬性文字斷行
說明:若使用html tag的title屬性,文字使用 (ASCII的\n)或 (ASCII的\r)來斷行,若用server control要做到同樣效果,如Panel的tooltip文字使用\n或\r或\r\n。
例:
//html title
<div id="pic" title="1. test1 2. test2"></div>
//server control
this.Panel1.ToolTip = "1. test1 \n2. test2";
參考資料:
http://www.dotblogs.com.tw/aquarius6913/archive/2011/02/01/21179.aspx
例:
//html title
<div id="pic" title="1. test1 2. test2"></div>
//server control
this.Panel1.ToolTip = "1. test1 \n2. test2";
參考資料:
http://www.dotblogs.com.tw/aquarius6913/archive/2011/02/01/21179.aspx
2014年2月25日 星期二
[ASP.NET] Server Control Table使用記錄
命名空間:
System.Web.UI.WebControls
語法:
<asp:Table borderwidth="1" id="tbTest" runat="server">
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblUserNo" runat="server" Text="" />
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblBirthday" runat="server" Text="" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtUserNo" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtBirthday" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtBirthday_CalendarExtender" runat="server"
Enabled="True" TargetControlID="txtBirthday" Format="yyyy/MM/dd">
</asp:CalendarExtender>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.table(v=vs.110).aspx
http://imagine-code.blogspot.tw/2013/07/aspnet_3.html
System.Web.UI.WebControls
語法:
<asp:Table borderwidth="1" id="tbTest" runat="server">
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblUserNo" runat="server" Text="" />
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblBirthday" runat="server" Text="" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtUserNo" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtBirthday" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtBirthday_CalendarExtender" runat="server"
Enabled="True" TargetControlID="txtBirthday" Format="yyyy/MM/dd">
</asp:CalendarExtender>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.table(v=vs.110).aspx
http://imagine-code.blogspot.tw/2013/07/aspnet_3.html
[ASP.NET] 連接Oracle
問題:
大部分ASP.NET網站搭配SQL Server較多,若DB使用Oracle,該怎麼做?
作法(使用oleDb):
0. 主機或local需安裝Oracle client,在tnsname.ora設定連Oracle Server服務資訊。
1. 在web.config的connectionStrings標籤內加入連線資訊,例:
<add name="OracleDBConn" connectionString="Provider=MSDAORA(OraOLEDB.Oracle);Data Source=service_name;Persist Security Info=True;User ID=user_id;Password=password"/>
2. 在DB存取class中,引用System.Data.OleDb命名空間;
3. 擷取連線字串(需引用System.Configuration命名空間):
private static string OracleDBConn = ConfigurationManager.ConnectionStrings["OracleDBConn"].ConnectionString;
4. 撰寫操作method,例:
public static DataTable ExecuteDataTable(string strQuery)
{
try
{
DataTable dtReturn = new DataTable();
using (OleDbConnection conn = new OleDbConnection(OracleDBConn))
{
using (OleDbDataAdapter sda = new OleDbDataAdapter(strQuery, conn))
{
sda.Fill(dtReturn);
return dtReturn;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.data.oledb(v=vs.110).aspx
http://c.ittoolbox.com/groups/technical-functional/csharp-l/connection-string-for-ms-access-in-c-3271615
大部分ASP.NET網站搭配SQL Server較多,若DB使用Oracle,該怎麼做?
作法(使用oleDb):
0. 主機或local需安裝Oracle client,在tnsname.ora設定連Oracle Server服務資訊。
1. 在web.config的connectionStrings標籤內加入連線資訊,例:
<add name="OracleDBConn" connectionString="Provider=MSDAORA(OraOLEDB.Oracle);Data Source=service_name;Persist Security Info=True;User ID=user_id;Password=password"/>
2. 在DB存取class中,引用System.Data.OleDb命名空間;
3. 擷取連線字串(需引用System.Configuration命名空間):
private static string OracleDBConn = ConfigurationManager.ConnectionStrings["OracleDBConn"].ConnectionString;
4. 撰寫操作method,例:
public static DataTable ExecuteDataTable(string strQuery)
{
try
{
DataTable dtReturn = new DataTable();
using (OleDbConnection conn = new OleDbConnection(OracleDBConn))
{
using (OleDbDataAdapter sda = new OleDbDataAdapter(strQuery, conn))
{
sda.Fill(dtReturn);
return dtReturn;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.data.oledb(v=vs.110).aspx
http://c.ittoolbox.com/groups/technical-functional/csharp-l/connection-string-for-ms-access-in-c-3271615
2014年1月26日 星期日
[.NET] 取得Server或Client IP
1. 取得Server IP語法:
using System.Net;
IPAddress ServerIP = IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
Response.Write("Server IP=" + ServerIP.ToString());
2. 取得Client IP
string strClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
string strClientIP = Request.UserHostAddress;
//使用代理伺服器
string strClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
參考資料:
http://blog.xuite.net/sunnysoap/r/25283108-C%23+%E5%A6%82%E4%BD%95%E5%8F%96%E5%BE%97%E6%9C%AC%E6%A9%9F(Server)%E7%9A%84IP
http://www.dotblogs.com.tw/jimmyyu/archive/2009/05/21/8493.aspx
http://bytes.com/topic/asp-net/answers/848515-how-get-client-ip-address-assigned-isp
http://dotnetstock.com/technical/how-to-get-ip-address-of-a-client-system-using-asp-net
http://csharpdotnetfreak.blogspot.com/2008/12/finding-ip-address-behind-proxy-using-c.html
http://forums.asp.net/t/1780050.aspx
using System.Net;
IPAddress ServerIP = IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
Response.Write("Server IP=" + ServerIP.ToString());
2. 取得Client IP
string strClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
string strClientIP = Request.UserHostAddress;
//使用代理伺服器
string strClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
參考資料:
http://blog.xuite.net/sunnysoap/r/25283108-C%23+%E5%A6%82%E4%BD%95%E5%8F%96%E5%BE%97%E6%9C%AC%E6%A9%9F(Server)%E7%9A%84IP
http://www.dotblogs.com.tw/jimmyyu/archive/2009/05/21/8493.aspx
http://bytes.com/topic/asp-net/answers/848515-how-get-client-ip-address-assigned-isp
http://dotnetstock.com/technical/how-to-get-ip-address-of-a-client-system-using-asp-net
http://csharpdotnetfreak.blogspot.com/2008/12/finding-ip-address-behind-proxy-using-c.html
http://forums.asp.net/t/1780050.aspx
2014年1月1日 星期三
[ASP.NET] 網頁導向Response.Redirect與Server.Transfer
說明:網頁導向有Response.Redirect與Server.Transfer兩種方法,有什麼不同?
說明:
Response.Redirect不會保留表單值,可導向外部網站,但送出兩次Request,一次給Source.aspx,一次給Destination.aspx。可用在get傳值。
例:
Response.Redirect("Destination.aspx?Value="+strValue);
Server.Transfer恰好相反,可保留表單值,但只限同一網站,Request一次效能較佳。
參考資料:
http://www.dotblogs.com.tw/jimmyyu/archive/2009/11/10/11503.aspx
說明:
Response.Redirect不會保留表單值,可導向外部網站,但送出兩次Request,一次給Source.aspx,一次給Destination.aspx。可用在get傳值。
例:
Response.Redirect("Destination.aspx?Value="+strValue);
Server.Transfer恰好相反,可保留表單值,但只限同一網站,Request一次效能較佳。
參考資料:
http://www.dotblogs.com.tw/jimmyyu/archive/2009/11/10/11503.aspx
2013年12月3日 星期二
[ASP.NET] Enable/Disable GridView裡的LinkButton
說明:在GridView的樣板裡放了LinkButton,並想根據點選LinkButton後紀錄的Status來繫結LinkButton最新的狀態(Enable/Disable)。
例:
Process_No Process_Name Check-in Check-out
1 test LinkButton1 LinkButton2
若Process Check-in後,則LinkButton1 Disable LinkButton2 Enable
作法:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnCheckIn = (Button)e.Row.FindControl("btnCheckIn");
Button btnCheckOut = (Button)e.Row.FindControl("btnCheckOut");
btnCheckIn.Enabled = false;
btnCheckOut.Enabled = false;
//取得繫結於GridView中各row的Check_Status值
string strCheckStatus = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Check_Status"));
//Initial
if (strCheckStatus == "0")
{
btnCheckIn.Enabled = true;
}
//Check in
else if (strCheckStatus == "1")
{
btnCheckOut.Enabled = true;
}
}
}
參考來源:
http://stackoverflow.com/questions/17207271/enable-and-disable-link-button-on-gridview
例:
Process_No Process_Name Check-in Check-out
1 test LinkButton1 LinkButton2
若Process Check-in後,則LinkButton1 Disable LinkButton2 Enable
作法:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnCheckIn = (Button)e.Row.FindControl("btnCheckIn");
Button btnCheckOut = (Button)e.Row.FindControl("btnCheckOut");
btnCheckIn.Enabled = false;
btnCheckOut.Enabled = false;
//取得繫結於GridView中各row的Check_Status值
string strCheckStatus = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Check_Status"));
//Initial
if (strCheckStatus == "0")
{
btnCheckIn.Enabled = true;
}
//Check in
else if (strCheckStatus == "1")
{
btnCheckOut.Enabled = true;
}
}
}
參考來源:
http://stackoverflow.com/questions/17207271/enable-and-disable-link-button-on-gridview
2013年11月13日 星期三
[ASP.NET] CheckBoxList取得多選之Value
說明:使用CheckBoxList,該如何取得多選之Value?使用SelectedValue只抓得到index最小的Value。
作法1-使用迴圈找Selected的Item:
code behind
StringBuilder sbTest = new StringBuilder();
for (int i = 0; i < cblTest.Items.Count; i++)
{
if (cblTest.Items[i].Selected)
{
sbTest.Append(cblTest.Items[i].Value.Trim() + ", ");
}
}
sbTest = sbTest.Remove(sbTest.Length - 2, 2);
作法2-覆寫CheckBoxList控制項的SelectedValue方法:
請參考IN91大文章:
http://www.dotblogs.com.tw/hatelove/archive/2009/01/13/6785.aspx
參考資料:
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20100319135604VSG
http://www.dotblogs.com.tw/hatelove/archive/2009/01/13/6785.aspx
作法1-使用迴圈找Selected的Item:
code behind
StringBuilder sbTest = new StringBuilder();
for (int i = 0; i < cblTest.Items.Count; i++)
{
if (cblTest.Items[i].Selected)
{
sbTest.Append(cblTest.Items[i].Value.Trim() + ", ");
}
}
sbTest = sbTest.Remove(sbTest.Length - 2, 2);
作法2-覆寫CheckBoxList控制項的SelectedValue方法:
請參考IN91大文章:
http://www.dotblogs.com.tw/hatelove/archive/2009/01/13/6785.aspx
參考資料:
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20100319135604VSG
http://www.dotblogs.com.tw/hatelove/archive/2009/01/13/6785.aspx
2013年11月4日 星期一
[ASP.NET] 解決DropDownList內ListItem Value重複的問題
說明:在設計DropDownList的清單項目時,一般是不會有Value相同的情況,如果有重複,DropDownList會傳回Index最前面的那筆ItemList,例:
<asp:DropDownList ID="ddlTest" runat="server" AutoPostBack="True">
<asp:ListItem Value="0">請選擇</asp:ListItem>
<asp:ListItem Value="1">台北</asp:ListItem>
<asp:ListItem Value="1">新北</asp:ListItem>
<asp:ListItem Value="2">桃園</asp:ListItem>
<asp:ListItem Value="2">新竹</asp:ListItem>
</asp:DropDownList>
//判斷PostBack的selectedIndex與原selectedIndex是否相同,不同則觸發SelectedIndexChanged 事件
<asp:DropDownList ID="ddlTest" runat="server" AutoPostBack="True">
<asp:ListItem Value="0">請選擇</asp:ListItem>
<asp:ListItem Value="1">台北</asp:ListItem>
<asp:ListItem Value="1">新北</asp:ListItem>
<asp:ListItem Value="2">桃園</asp:ListItem>
<asp:ListItem Value="2">新竹</asp:ListItem>
</asp:DropDownList>
點選新北,此時DropDownList卻顯示台北,而且無法觸發 SelectedIndexChanged 事件。
作法:參考ASP.NET魔法學院的作法,override DropDownList的方法,將VB版本改為C#:
1. 新增一專案,在類別內加入System.Web.UI.WebControls參考
namespace WebControls
{
public class CDropDownList: DropDownList
{
//將DropDownList的selectedIndex也PostBack回Server端
//將DropDownList的selectedIndex也PostBack回Server端
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
bool blAutoPostBack = false;
string strScript = string.Empty;
blAutoPostBack = this.AutoPostBack;
this.AutoPostBack = false;
base.AddAttributesToRender(writer);
if (blAutoPostBack)
{
base.Attributes.Remove("onchange");
strScript = String.Format("__doPostBack('{0}',{1})", this.ClientID, "this.selectedIndex");
writer.AddAttribute(HtmlTextWriterAttribute.Onchange, strScript);
this.AutoPostBack = true;
}
}
//判斷PostBack的selectedIndex與原selectedIndex是否相同,不同則觸發SelectedIndexChanged 事件
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
string[] strValues = new string[35]; //可自己定義陣列大小
int iSelectedIndex = 0;
this.EnsureDataBound();
strValues = postCollection.GetValues(postDataKey);
if (strValues != null && Page.Request.Form["__EVENTARGUMENT"].ToString() != "")
{
iSelectedIndex = Convert.ToInt32(this.Page.Request.Form["__EVENTARGUMENT"]);
}
if (this.SelectedIndex != iSelectedIndex)
{
base.SetPostDataSelection(iSelectedIndex);
return true;
}
return false;
}
}
}
2. 在web專案加入此專案建置後的dll,在工具箱->選擇項目->加入該元件即可,可自訂前置詞(TagPrefix),定義控制項所在命名空間的別名,預設為cc1。
參考資料:
2013年10月24日 星期四
[ASP.NET] RadioButtonList內Item改回水平排列
說明: 一般使用RadioButtonList控制項,其Item預設為垂直排列(vertical),例:
o 選項一
o 選項二
該怎麼改成水平排列(horizontal)?
o 選項一 o 選項二
作法:
只要將此控制項的RepeatDirection屬性改為horizontal即可。
參考資料:
http://blog.yam.com/highscope/article/31505801
o 選項一
o 選項二
該怎麼改成水平排列(horizontal)?
o 選項一 o 選項二
作法:
只要將此控制項的RepeatDirection屬性改為horizontal即可。
參考資料:
http://blog.yam.com/highscope/article/31505801
2013年10月23日 星期三
[ASP.NET] 子視窗日曆傳值回母視窗控制項上
說明:點選母視窗上的TextBox後,彈出一日曆子視窗,點選日期後回傳至母視窗TextBox上。
作法:
Parent.aspx
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function SetDate(ClientID)
{
var Url = '../modaldialog/SetDate.aspx?DialogClientID=' + ClientID;
window.open(Url, 'Calendar', 'width=335, height=170');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtDate" runat="server" onclick="SetDate(this.id)"></asp:TextBox>
</form>
</body>
Son.aspx
protected void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
if (Request.QueryString["DialogClientID"] != null)
{
string strClientID = Request["DialogClientID"].ToString().Trim();
StringBuilder sbJScript = new StringBuilder();
sbJScript.Append("window.opener.document.getElementById('" + strClientID + "').value = '" + this.Calendar1.SelectedDate.ToString("yyyy/MM/dd") + "';");
sbJScript.Append("window.close();");
ClientScript.RegisterStartupScript(this.GetType(), "ReturnValue", sbJScript.ToString(), true);
}
}
參考資料:
http://social.msdn.microsoft.com/Forums/zh-TW/b415ff68-2dcc-4e1c-b202-e41b4e29f8a9/a-popup-b-a-
作法:
Parent.aspx
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function SetDate(ClientID)
{
var Url = '../modaldialog/SetDate.aspx?DialogClientID=' + ClientID;
window.open(Url, 'Calendar', 'width=335, height=170');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtDate" runat="server" onclick="SetDate(this.id)"></asp:TextBox>
</form>
</body>
Son.aspx
protected void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
if (Request.QueryString["DialogClientID"] != null)
{
string strClientID = Request["DialogClientID"].ToString().Trim();
StringBuilder sbJScript = new StringBuilder();
sbJScript.Append("window.opener.document.getElementById('" + strClientID + "').value = '" + this.Calendar1.SelectedDate.ToString("yyyy/MM/dd") + "';");
sbJScript.Append("window.close();");
ClientScript.RegisterStartupScript(this.GetType(), "ReturnValue", sbJScript.ToString(), true);
}
}
參考資料:
http://social.msdn.microsoft.com/Forums/zh-TW/b415ff68-2dcc-4e1c-b202-e41b4e29f8a9/a-popup-b-a-
2013年10月22日 星期二
[ASP.NET] MasterPage套用多語系
說明:一般ASP.NET網頁都是override InitializeCulture method來轉換語系,但因MasterPage是繼承MasterPage class(UserControl),無提供InitializeCulture method。
作法:
1. 自訂一BasePage class(放於App_Code)並繼承Page class,在BasePage中override InitializeCulture method,再使各page從繼承Page改為namespace.BasePage,例:
BasePage.cs
namespace Web
{
public class BasePage : Page
{
protected override void InitializeCulture()
{
string culture = Session["culture"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.InitializeCulture();
}
}
}
再搭配如DropDownList等控制項供選擇,例:
xxx.aspx
<asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="True" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="zh-TW" Text="<%$ Resources:PageResource, LanguageZh %>"></asp:ListItem>
<asp:ListItem Value="en-US" Text="<%$ Resources:PageResource, LanguageEn %>"></asp:ListItem></asp:DropDownList>
xxx.aspx.cs
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddlLanguage.SelectedIndex > 0)
{
Session["culture"] = this.ddlLanguage.SelectedValue;
//reload request page
Server.Transfer(Request.Path);
}
}
參考資料:
http://stackoverflow.com/questions/11805897/masterpage-initializeculture-no-suitable-method-found-to-override-error
2. 透過global.asax。
作法:
1. 自訂一BasePage class(放於App_Code)並繼承Page class,在BasePage中override InitializeCulture method,再使各page從繼承Page改為namespace.BasePage,例:
BasePage.cs
namespace Web
{
public class BasePage : Page
{
protected override void InitializeCulture()
{
string culture = Session["culture"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.InitializeCulture();
}
}
}
再搭配如DropDownList等控制項供選擇,例:
xxx.aspx
<asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="True" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="zh-TW" Text="<%$ Resources:PageResource, LanguageZh %>"></asp:ListItem>
<asp:ListItem Value="en-US" Text="<%$ Resources:PageResource, LanguageEn %>"></asp:ListItem></asp:DropDownList>
xxx.aspx.cs
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddlLanguage.SelectedIndex > 0)
{
Session["culture"] = this.ddlLanguage.SelectedValue;
//reload request page
Server.Transfer(Request.Path);
}
}
參考資料:
http://stackoverflow.com/questions/11805897/masterpage-initializeculture-no-suitable-method-found-to-override-error
2. 透過global.asax。
2013年10月14日 星期一
[ASP.NET/ Crystal Report] 實作multiple table資料來源且table間無關聯的報表
說明:使用Crystal Reports實做一報表,繫結DB table為2個以上,且table之間無關聯,
作法:
1. 使用DataSet建立報表資料結構,新增DataTable以對應不同DB table,可不需建立DataTableAdapter方法
2. 新增Crystal Report檔,使用資料庫專家->ADO.NET資料集,選取建立的table結構
3. 將資料庫欄位拉至報表上
4. 新增一web page以呈現報表,拉一CrystalReportViewer控制項,依需求調整控制項面板
5. 在code behind繫結資料來源:
例:
//需import該dll
using CrystalDecisions.CrystalReports.Engine;
private ReportDocument rdReport;
protected void Page_Load(object sender, EventArgs e)
{
rdReport = new ReportDocument();
if (!IsPostBack)
{
BindReport();
}
}
private void BindReport()
{
DataSet dsReport = GetReportData();
string strRptName = Page.MapPath("ReportView.rpt");
rdReport.Load(strRptName);
rdReport.SetDataSource(dsReport);
CrystalReportViewer1.ReportSource = rdReport;
CrystalReportViewer1.DataBind();
}
private DataSet GetReportData()
{
DataSet dsReturn = new DataSet();
DataTable dtTemp = null;
//此處以DataTable回傳各DB table資料,若table之間有關聯,可以join方式回傳即可,無關聯則取得各table資料,再依Step1建立之table name加進DataSet中即可
dtTemp = 各sql回傳資料;
dtTemp.TableName = "Step1中建立的table name";
dsReturn.Tables.Add(dtTemp);
return dsReturn;
}
參考資料:
http://csharp.net-informations.com/dataset/dataset-multiple-tables-sqlserver.htm
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20110419171449396
http://www.functionx.com/csharp2/dataset/Lesson02b.htm
作法:
1. 使用DataSet建立報表資料結構,新增DataTable以對應不同DB table,可不需建立DataTableAdapter方法
2. 新增Crystal Report檔,使用資料庫專家->ADO.NET資料集,選取建立的table結構
3. 將資料庫欄位拉至報表上
4. 新增一web page以呈現報表,拉一CrystalReportViewer控制項,依需求調整控制項面板
5. 在code behind繫結資料來源:
例:
//需import該dll
using CrystalDecisions.CrystalReports.Engine;
private ReportDocument rdReport;
protected void Page_Load(object sender, EventArgs e)
{
rdReport = new ReportDocument();
if (!IsPostBack)
{
BindReport();
}
}
private void BindReport()
{
DataSet dsReport = GetReportData();
string strRptName = Page.MapPath("ReportView.rpt");
rdReport.Load(strRptName);
rdReport.SetDataSource(dsReport);
CrystalReportViewer1.ReportSource = rdReport;
CrystalReportViewer1.DataBind();
}
private DataSet GetReportData()
{
DataSet dsReturn = new DataSet();
DataTable dtTemp = null;
//此處以DataTable回傳各DB table資料,若table之間有關聯,可以join方式回傳即可,無關聯則取得各table資料,再依Step1建立之table name加進DataSet中即可
dtTemp = 各sql回傳資料;
dtTemp.TableName = "Step1中建立的table name";
dsReturn.Tables.Add(dtTemp);
return dsReturn;
}
參考資料:
http://csharp.net-informations.com/dataset/dataset-multiple-tables-sqlserver.htm
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20110419171449396
http://www.functionx.com/csharp2/dataset/Lesson02b.htm
2013年10月1日 星期二
[ASP.NET] 如何在GridView加上CheckBox全選與取消全選
說明:
在GridView加上CheckBox針對目標列資料勾選或全選以刪除資料。
作法:
//xxx.aspx
<GridView>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="cbxHead" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbxRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
//xxx.aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox cbxHead = (CheckBox)e.Row.FindControl("cbxHead");
cbxHead.Attributes.Add("onclick", "for(i=0;i<" + GridView1.ClientID + ".all.tags('input').length;i++){if (" + GridView1.ClientID + ".all.tags('input')[i].type=='checkbox'){" + GridView1.ClientID + ".all.tags('input')[i].checked=checked}}");
}
在GridView加上CheckBox針對目標列資料勾選或全選以刪除資料。
作法:
//xxx.aspx
<GridView>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="cbxHead" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbxRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
//xxx.aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox cbxHead = (CheckBox)e.Row.FindControl("cbxHead");
cbxHead.Attributes.Add("onclick", "for(i=0;i<" + GridView1.ClientID + ".all.tags('input').length;i++){if (" + GridView1.ClientID + ".all.tags('input')[i].type=='checkbox'){" + GridView1.ClientID + ".all.tags('input')[i].checked=checked}}");
}
}
2013年9月26日 星期四
[ASP.NET/AjaxToolKit] 使用CalendarExtender遇到問題紀錄
紀錄一下,使用上遇到的問題:
1. 找不到任何適用特定文化特性或中性文化特性的資源。請確定您已在編譯時期正確地將 "AjaxControlToolkit.Properties.Resources.resources" 嵌入或連結至組件 "AjaxControlToolkit" 中,或所有需要的附屬組件均為可載入且已完整簽署。
Ans: 無加入ToolkitScriptManager或ScriptManager控制項。
2. 加入ToolkitScriptManager控制項後,發生MasterPage的JavaScript或JQuery運作不正常
做法:
1. 在ScriptManager或ToolkitScriptManager控制項加上ScriptMode="Release",此屬性用來決定用戶端指令碼程式庫該使用debug抑或Release的版本,ScriptMode預設為Auto,會跟著web.config的deployment retail的屬性走,預設為false,因此ScriptMode="Debug"。AjaxToolKit官網也建議將ScriptMode="Release",http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ToolkitScriptManager/ToolkitScriptManager.aspx
//xxx.aspx
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release"></asp:ToolkitScriptManager>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtDate"></asp:CalendarExtender>
2. 也可能是以下板友列出的原因:
http://social.msdn.microsoft.com/Forums/zh-TW/81016eba-6e82-479a-b426-fc53f8b1f3ac/calendarextender-
參考資料
http://weblogs.asp.net/lorenh/archive/2008/02/15/speed-up-load-time-of-ajax-control-toolkit-controls-while-debugging.aspx
http://msdn.microsoft.com/zh-tw/library/system.web.ui.scriptmanager.scriptmode.aspx
http://msdn.microsoft.com/zh-tw/library/ms228298.aspx
1. 找不到任何適用特定文化特性或中性文化特性的資源。請確定您已在編譯時期正確地將 "AjaxControlToolkit.Properties.Resources.resources" 嵌入或連結至組件 "AjaxControlToolkit" 中,或所有需要的附屬組件均為可載入且已完整簽署。
Ans: 無加入ToolkitScriptManager或ScriptManager控制項。
2. 加入ToolkitScriptManager控制項後,發生MasterPage的JavaScript或JQuery運作不正常
做法:
1. 在ScriptManager或ToolkitScriptManager控制項加上ScriptMode="Release",此屬性用來決定用戶端指令碼程式庫該使用debug抑或Release的版本,ScriptMode預設為Auto,會跟著web.config的deployment retail的屬性走,預設為false,因此ScriptMode="Debug"。AjaxToolKit官網也建議將ScriptMode="Release",http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ToolkitScriptManager/ToolkitScriptManager.aspx
//xxx.aspx
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release"></asp:ToolkitScriptManager>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtDate"></asp:CalendarExtender>
2. 也可能是以下板友列出的原因:
http://social.msdn.microsoft.com/Forums/zh-TW/81016eba-6e82-479a-b426-fc53f8b1f3ac/calendarextender-
參考資料
http://weblogs.asp.net/lorenh/archive/2008/02/15/speed-up-load-time-of-ajax-control-toolkit-controls-while-debugging.aspx
http://msdn.microsoft.com/zh-tw/library/system.web.ui.scriptmanager.scriptmode.aspx
http://msdn.microsoft.com/zh-tw/library/ms228298.aspx
訂閱:
文章 (Atom)