2009年11月17日 星期二

RequiredFieldValidator的使用(欄位驗證)

效果:




RequiredFieldValidator簡介
網址:http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.requiredfieldvalidator%28VS.80%29.aspx

基本設定
1、在Textbox旁放RequiredFieldValidator物件
2、RequiredFieldValidator屬性
2.1 ErrorMessage=要顯示的內容
2.2 ControlToValidate=要驗證的物件名稱(TextboxIDName)

補充:
如果不是所有button都要自動驗證動作 ,在該button之屬性設CausesValidation="False"即可。


2009年9月29日 星期二

針對SqlCommandBuilder再進一步的使用

使用SqlCommandBuilder,新資料可以整筆新增,但若已存在且有修改的資料,並不會寫回至資料庫中,必須設下列指令才可達成,刪除亦同理作法。

SqlCommandBuilder builder = new SqlCommandBuilder(cmdSQL);
builder.RefreshSchema();

cmdSQL.UpdateCommand = builder.GetUpdateCommand();
cmdSQL.UpdateCommand = new SqlCommand("UPDATE TableName SET Field2=@para2 WHERE Field2=@para2;", usrcn);

cmdSQL.UpdateCommand.Parameters.Add("@para1", SqlDbType.NVarChar,50, "Field");

cmdSQL.UpdateCommand.Parameters.Add("@para2",SqlDbType.NVarChar,50, "Field");
cmdSQL.Update(ds_base, "Table");

注意:SqlCommandBuilder資料來源一定要有primary key欄位值

參考網址:http://msdn.microsoft.com/zh-tw/library/system.data.sqlclient.sqldataadapter.updatecommand(VS.80).aspx

2009年6月11日 星期四

ExcelImportDB(整筆新增)

取得excel資料
string strCon = @" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + 檔案路徑+ ";Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";
DataSet ds_excel = new DataSet();
OleDbConnection objConn = new OleDbConnection(strCon);
objConn.Open();
OleDbDataAdapter odda = new OleDbDataAdapter("Select * from [sheet1$]", objConn);
odda.Fill(excel , "Sheet1");
objConn.Close();

定義table的欄位及資料型態(直接複製db的table)
DataSet ds_org=new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
sqlconn.Open();
SqlCommand cmd_original = new SqlCommand(@"SELECT fields1,fields2,fields3,fields4......
FROM table", sqlconn);//參考的資料表

SqlDataAdapter sda = new SqlDataAdapter(cmd_original);
sda.Fill(ds_org, "ORG");

DataTable dt = ds_org.Tables[0].Copy();//將架構和資料型態複製給定義的dt

將excel資料新增到dt(縱向新增)
for (int i = 1; i < ds_excel.Tables[0].Columns.Count; i++)
{
row = dt.NewRow();
row["fields1"] = ds_excel.Tables[0].Rows[0][i].ToString();
row["fields2"] = ds_excel.Tables[0].Rows[2][i].ToString();
.......
dt.Rows.Add(row);
}

將資料新增至DB
SqlCommandBuilder builder = new SqlCommandBuilder(sda);
builder.RefreshSchema();

sda.Update(dt);

ds_excel.Dispose();
ds_org.Dispose();
sda.Dispose();
sqlconn.Close();

2009年6月10日 星期三

數值進行四捨六入五取雙的判斷

要呈現的結果:
1.4→1
1.6→2
1.5→2
2.5→2

ALTER FUNCTION [dbo].[FN_ChangeNumber](@money decimal(18,2))
RETURNS Int
AS

BEGIN
declare @intvalue int,@decimalvalue int,@retvalue int

--取整數和小數第一位
select @intvalue=substring(Convert(nvarchar(20),@money),1, charindex('.', Convert(nvarchar(20),@money))-1) , @decimalvalue=substring(substring(Convert(nvarchar(20),@money), charindex('.', Convert(nvarchar(20),@money))+1 , len(Convert(nvarchar(20),@money))-charindex('.', Convert(nvarchar(20),@money))) ,1,1)

if(@decimalvalue<=4)begin set @retvalue=@intvalue end

if(@decimalvalue>=6)begin set @retvalue=@intvalue+1 end

if(@decimalvalue=5)begin
if(@intvalue%2=0) set @retvalue=@intvalue
else set @retvalue=@intvalue+1
end

RETURN @retvalue
END

感謝Keen協助

2009年4月2日 星期四

將圖或FLASH檔存入資料庫,並且顯示在網頁上的用法

建立一個FileUpload物件,命名為FileUp

儲檔CS:
==================================================
int imgLen = FileUp.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
imgBinaryData = FileUp.FileBytes;
SqlConnection usrcn = new SqlConnection();
usrcn.ConnectionString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd_file = new SqlCommand();
cmd_file.Connection = usrcn;
cmd_file.CommandText = string.Format(@"Update ImageTB set Image=@image where imgid={0}", imgid);
cmd_file.CommandType = CommandType.Text;
//欄位型態必為Image
cmd_file.Parameters.Add("@image", SqlDbType.Image).Value = imgBinaryData;
usrcn.Open();
cmd_file.ExecuteNonQuery();
usrcn.Close();
==================================================

顯示:

ps1:無論哪個設定,請務必設定寬高,使得圖檔大小一致化
ps2:ImageHandler.ashx用法請參考下列網址!
ps3:ImageHandler.ashx若要帶參數,如同一般網頁設定方式即可!取值方式:context.Request["type"].ToString()

參考網址:
http://blog.xuite.net/alwaysfuturevision/liminzhang/9538604
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20061012135834YHQ&fumcde=FUM20041006161839LRJ&rplcnt=29
http://www.blueshop.com.tw/board/show.asp?subcde=BRD2008061010385466M&fumcde=FUM20050124192253INM

感謝Polly協助

2009年1月15日 星期四

在Gridview,針對Header粗體的處理

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header)
{
foreach(TableCell cell in e.Row.Cells)
cell.Attributes.Add("style","FONT-WEIGHT:normal");
}
}




參考:http://topic.csdn.net/t/20060712/22/4876677.html#

2009年1月8日 星期四

使用SqlDataSource時,請注意

當select的語法很短及易,就會利用SqlDataSource來達成查詢資料的功效
.aspx
SqlDataSource
ConnectionString="連結字串"
SelectCommand="SQL語法"
SelectCommandType="text"

.cs
SqlDataSource.SelectParameters.Clear();
SqlDataSource.SelectParameters.Add("keyword", TypeCode.String, tbx_keyword.Text.Trim());
SqlDataSource.Select(new DataSourceSelectArguments());

正常來說,以上的設定就可以完成查詢的功能,但若發現如無查詢條件時,應該獲得所有的資料清單,卻無資料;反之,就能獲得查詢的資料清單,這時就要多設定
SqlDataSource.SelectParameters["keyword"].ConvertEmptyStringToNull = false;

因當SqlDataSource遇到空字串時,會自動轉換成null,所以要關閉此功能屬性

2009年1月7日 星期三

在GridView,針對Button的設定

使用GridView時,針對Button的設定,如果只需一個參數就好解決,但遇到要多個參數就有點麻煩了,經過這段時間的磨練,有兩種方式可以設定,紀錄一下

第一種
.aspx
GridView
< id="btn_Delete" runat="server" text="刪除" onclick="Del_Click">

.cs
GridView_RowDataBound
if (e.Row.RowType == DataControlRowType.DataRow)
Button btn_Delete = (Button)e.Row.FindControl("btn_Delete"); btn_Delete.Attributes.Add("OnClick", "if (confirm('您確定要刪除嗎?')==false) {return false;}");
btn_Delete.Attributes["id"] = DataBinder.Eval(e.Row.DataItem, "id").ToString();
btn_Delete.Attributes["sn"] = DataBinder.Eval(e.Row.DataItem, "sn").ToString();


protected void Del__Click(object sender, EventArgs e)
{
Button btnDel = (Button)sender;
string id= btnDel.Attributes["id"].ToString();
string sn= btnDel.Attributes["sn"].ToString();

//其他作業
}


第二種
.cs
GridView_RowDataBound

if (e.Row.RowType == DataControlRowType.DataRow)
Button btn_Delete = (Button)e.Row.FindControl("btn_Delete");
btn_addsub.CommandName = "Delete";
btn_addsub.CommandArgument = string.Format("{0},{1}", DataBinder.Eval(e.Row.DataItem, "id"), DataBinder.Eval(e.Row.DataItem, "sn"));


GridView_RowCommand
switch (e.CommandName)
{
case "Delete":
string[] aString = Convert.ToString(e.CommandArgument).Split(',');
btnDelete(aString[0], aString[1]);
break;
}


private void btnDelete(string id, string sn)
{
}

網頁也可有訊問方塊MessageBox:Yes No

新增一頁Messagebox.aspx
設定
建立:兩個Button:「是」,「否」
程式碼:
protected void btn_Y_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "select", string.Format("returnValue='{0}';window.close();", "Yes"), true);
}
protected void btn_N_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "select", string.Format("returnValue='{0}';window.close();", "No"), true);
}


呼叫的頁面
.aspx
javascript
function doIsSave()
{
var url = 'Messagebox.aspx';
var retValue = window.showModalDialog(url, '提示', 'resizable:no;scroll:no;status:no;dialogHeight=80pt;dialogWidth=300pt');
if(retValue != null && retValue !="")
{ //alert(retValue);
document.getElementById("h_issave").value=retValue;
}
}


.cs
page_Load:Button.Attributes.Add("OnClick", "javascript:doIsSave();");

protected void Button_Click(object sender, EventArgs e)
{
if (h_issave.Value == "Yes")
if (h_issave.Value == "No")
}