2009年12月20日 星期日

動態產生 datagrid Columns - TextBox

動態產生 datagrid Columns - TextBox

之前遇到的CASE是 checkbox:


http://roxsu.blogspot.com/2009/01/datagrid-columns.html


這次則是TextBox, 而且是在同TemplateColumn下產生


ItemTemplate及EditItemTemplate


首先建立一個介面(temptext.vb)如下:




Public Class temptext
Implements ITemplate

Private plbnID As String
Private ItemType As ListItemType
Private intW As Unit

Public Sub New(ByVal lbnID As String, ByVal item_type As ListItemType, ByVal inW As Integer)
plbnID = lbnID
ItemType = item_type
intW = New Unit(inW)
End Sub

Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements

System.Web.UI.ITemplate.InstantiateIn
Select Case ItemType
Case ListItemType.Item
Dim lbn As New Label
lbn.ID = "L" + plbnID
lbn.Text = ""
lbn.Visible = True
AddHandler lbn.DataBinding, AddressOf TemplateControl_DataBinding
container.Controls.Add(lbn)
Case ListItemType.EditItem
Dim lbn As New TextBox
lbn.ID = plbnID
lbn.Text = ""
lbn.Visible = True
lbn.Width = intW
AddHandler lbn.DataBinding, AddressOf TemplateControl_DataBinding
container.Controls.Add(lbn)
End Select
End Sub

Private Sub TemplateControl_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
Select Case ItemType
Case ListItemType.Item
Dim lc As Label
lc = CType(sender, Label)
Dim container As DataGridItem
container = CType(lc.NamingContainer, DataGridItem)
lc.Text = DataBinder.Eval(container.DataItem, plbnID)
Case ListItemType.EditItem
Dim lc As TextBox
lc = CType(sender, TextBox)
Dim container As DataGridItem
container = CType(lc.NamingContainer, DataGridItem)
lc.Text = DataBinder.Eval(container.DataItem, plbnID)
End Select
End Sub
End Class



和前例一樣


在datagrid Bind資料前定義column:


先將column資料讀入dataset: ds_bar


再分別新增datagrid : grdResults.Columns


及mytable.Columns





...
Dim myTable As DataTable = New DataTable
myTable.TableName = "reg"
myTable.Columns.Add(New DataColumn("tgl_sno", GetType(Integer)))
myTable.Columns.Add(New DataColumn("tgl_year", GetType(Integer)))
Dim v_bn As String
Dim i As Integer
Dim vi As Integer = 0
Dim v_col As TemplateColumn
For i = 0 To ds_bar.Tables(0).Rows.Count - 1
v_bn = ds_bar.Tables(0).Rows(i).Item

("cuki_kind").ToString.Trim
vi += 1
v_col = New TemplateColumn
If v_bn = "" Then
v_col.HeaderText = "None"
set_lab(vi, "None") ' 註0
Else
v_col.HeaderText = v_bn
set_lab(vi, v_bn)
End If
v_col.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
v_col.ItemTemplate = New temptext("tgl_psn" + Right((100 +

vi).ToString.Trim, 2), ListItemType.Item, 80)
v_col.EditItemTemplate = New temptext("tgl_psn" + Right((100 +

vi).ToString.Trim, 2), ListItemType.EditItem, 80)
grdResults.Columns.Add(v_col)
myTable.Columns.Add(New DataColumn("tgl_psn" + Right((100 +

vi).ToString.Trim, 2), GetType(Integer)))
If vi > 10 Then ' 註1
Exit For
End If
Next
txt_regcnt.Text = vi '註2
......


Sub set_lab(ByVal vi As Integer, ByVal v_nn As String)
Dim v_lab As Label = CType(Page.FindControl("lab_" + vi.ToString), Label)
v_lab.Text = v_nn
End Sub



註0: 再增行之動態LABEL.
註1: 暫訂最多10欄

而資料的取得要用Request.Form:


...
Dim da As SqlDataAdapter
Dim r As DataRow
Dim ds As DataSet = New DataSet
...
' SQL 字串及 GetDataAdapter
...
da.Fill(ds)
r = ds.Tables(0).Rows(0)
Dim cmdB As SqlCommandBuilder = New SqlCommandBuilder(da)
If inttcr_month.ToString.Length <> 0 Then
r("tgl_year") = inttcr_month
Else
r("tgl_year") = ""
End If
Dim ii As Integer
Dim v_uid As String = grdResults.Items

(e.Item.ItemIndex).UniqueID + ":tgl_psn"
Dim v_fld As String
Dim v_val As Integer
For ii = 1 To CInt(txt_regcnt.Text) '註2
v_val = Request.Form(v_uid + Right((ii +

100).ToString, 2))
v_fld = "tgl_psn" + Right((ii + 100).ToString, 2)
r(v_fld) = v_val
Next
da.Update(ds)
grdResults.EditItemIndex = -1
...



註2: LOAD將欄位數記錄及使用UPDATE在迴圈
在再增程序也可以用到:


...
Dim ii As Integer
Dim v_fld As String
Dim v_val As Integer
For ii = 1 To CInt(txt_regcnt.Text)
Dim v_txt As TextBox = CType(Page.FindControl("txt_" + ii.ToString), TextBox)
v_val = swfun.chk_v(v_txt.Text)
v_fld = "tgl_psn" + Right((ii + 100).ToString, 2)
r(v_fld) = v_val
Next
ds.Tables(0).Rows.Add(r)
da.Update(ds)
...

2009年11月12日 星期四

日期型態SQL更新

ASPX 原始碼中在 update 或是 insert parameter 中

將 DBType="date" 改成 DBtype="datetime"

2009年11月2日 星期一

從URL讀取網頁

Imports System.Net
Imports System.IO

Module Test

Sub Main()
Dim sURL As String
sURL = "http://msdn.microsoft.com%22
Try
Dim objNewRequest As WebRequest = HttpWebRequest.Create(sURL)
Dim objResponse As WebResponse = objNewRequest.GetResponse
Dim objStream As New StreamReader(objResponse.GetResponseStream())
Console.WriteLine(objStream.ReadToEnd())
Catch eUFE As UriFormatException
Console.WriteLine(eUFE.Message)
Catch eWEB As WebException
Console.WriteLine(eWEB.Message)
Catch e As Exception
Console.WriteLine(e.ToString)
End Try
End Sub
End Module

轉自: http://www.java2s.com

2009年11月1日 星期日

2009年10月30日 星期五

VS2008 pageLayout FlowLayout GridLayout

VS2008 pageLayout

設定方式:
工具 - 選項 - CSS 樣式 - 利用貼上......絕對位置.
(用物件上方白色標籤移動)

2009年10月27日 星期二

VS2008 ftp file UPLOAD

With the FtpWebRequest and FtpWebResponse classes:

Private Sub Upload(ByVal source As String, ByVal target As String, _
ByVal credential As NetworkCredential)
Dim request As FtpWebRequest = _
DirectCast(WebRequest.Create(target), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = credential
Dim reader As New FileStream(source, FileMode.Open)
Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte
reader.Read(buffer, 0, buffer.Length)
reader.Close()
request.ContentLength = buffer.Length
Dim stream As Stream = request.GetRequestStream
stream.Write(buffer, 0, buffer.Length)
stream.Close()
Dim response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse)
MessageBox.Show(response.StatusDescription, "File Uploaded")
response.Close()
End Sub

Dim credential As New NetworkCredential("username", "password")
Upload("test.zip", "ftp://myftp.net/test.zip%22, credential)

轉自: VB.NET

VS2008 SQL連結字串更新

VS2003:
WEB.CONFIG
    <appSettings>
        <add key="SQL_ConnectionString" value="Persist Security Info=True;User ID=sa;Initial Catalog=DDD;Data Source=SSS"/>

VB
            strConStr = System.Configuration.ConfigurationSettings.AppSettings("SQL_ConnectionString").ToString()

VS2008:
WEB.CONFIG
    <connectionStrings>
        <add name="SQL_ConnectionString" connectionString="Persist Security Info=True;User ID=sa;Initial Catalog=DDD;Data Source=SSS"/>

VB
Imports System.Configuration

            strConStr = ConfigurationManager.ConnectionStrings("SQL_ConnectionString").ConnectionString

2009年10月13日 星期二

如何關閉瀏覽器不詢問, 直接關閉?

一般開新視窗有:
如果用 target="_blank" 開啟視窗 則會出現提示
假如用window.open 開啟視窗 則關閉時 不會出現提示

如果用 target="_blank" 開啟視窗,
關閉時 不出現提示可以用:

window.open('','_self','');
window.close();

2009年6月9日 星期二

言之有理?

一.
記得兒子的國語考卷有一個問答題:
如果你是孔融你會讓梨嗎? 為什麼?
兒子的答案是: 會, 因為我不喜歡吃梨.

二.
同事從巴里島渡假回來, 正忙著處理一堆軟體設計需求.
我調侃她說: "誰教有人去晒太陽不帶NoteBook!"
她很正經的回答: "我有帶啊! 但是只有Lobby可以上網,
而且Lobby蚊子超多的."
我好奇的問: "那房間呢?"
她說: "房間雖然沒有蚊子但不能上網."
我追問: "房間有紗門嗎? 為什麼房間就沒有蚊?"
她說: "沒有啊! 陽台也很大, 連紗窗都沒有!"
"對啊! 為什麼我沒想到"
"那裡Lobby蚊子超多, 房間就是沒有蚊子?"
我若有所悟: "那可能是因為蚊子都沒付房錢的關係吧!"
她:-~

2009年6月6日 星期六

Tooltip Of Javascript

一個好用的Javascript Tooptip:(Sorry已經忘了出處)

1. 先加入 mytooltip.js

2. 在</HEAD>前新增一個css:

<style type="text/css">
.Text { FONT-WEIGHT: normal; FONT-SIZE: 8pt; COLOR: #333333; FONT-STYLE: normal; FONT-FAMILY: Verdana, Arial, Sans-serif, 'Times New Roman'; TEXT-DECORATION: none }
.toolTip { FONT-SIZE: 8pt; FILTER: alpha(opacity=70); FONT-FAMILY: Verdana, Arial, Sans-serif, 'Times New Roman'; -moz-opacity: 0.7; opacity: 0.7 }
</style>

</HEAD>

3. <body onload="initToolTips();">

4. body 下加一個

<div id="toolTipLayer" style="RIGHT:0px; LEFT:0px; VISIBILITY:hidden; POSITION:absolute"></div>

5. 在要顯示的物件上加MouserOver 及 MouserOut:

<asp:Image id="Image1" STYLE='CURSOR:hand' ImageUrl="../images/show.gif" runat="server" onMouseOver="toolTip('Hello This is Tooltips', '#FFFFFF', 'Green');" onMouseOut="toolTip();"></asp:Image>

(當然不一定要asp:物件

好像還可以Show圖, 用到再來看清楚好了...)

 

註: mytooltip.js 原始碼

//browser detection
    var agt=navigator.userAgent.toLowerCase();
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav6 = (is_nav && (is_major == 5));
    var is_nav6up = (is_nav && (is_major >= 5));
    var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
//browser detection
    var agt=navigator.userAgent.toLowerCase();
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav6 = (is_nav && (is_major == 5));
    var is_nav6up = (is_nav && (is_major >= 5));
    var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
//tooltip Position
var offsetX = 0;
var offsetY = -25;
var opacity = 100;
var toolTipSTYLE;

function initToolTips(){
  if(document.getElementById){
          toolTipSTYLE = document.getElementById("toolTipLayer").style;
  }
  if(is_ie || is_nav6up)
  {
    toolTipSTYLE.visibility = "visible";
    toolTipSTYLE.display = "none";
    document.onmousemove = moveToMousePos;
  }
}
function moveToMousePos(e)
{
  if(!is_ie){
    x = e.pageX;
    y = e.pageY;
  }else{
    x = event.x + document.body.scrollLeft;
    y = event.y + document.body.scrollTop;
  }

  toolTipSTYLE.left = x + offsetX+'px';
  toolTipSTYLE.top = y + offsetY+'px';
  return true;
}

function toolTip(msg, fg, bg)
{
  if(toolTip.arguments.length < 1) // if no arguments are passed then hide the tootip
  {
    if(is_nav4)
        toolTipSTYLE.visibility = "hidden";
    else
        toolTipSTYLE.display = "none";
  }
  else // show
  {
    if(!fg) fg = "#777777";
    if(!bg) bg = "#ffffe5";
    var content = '<table border="0" cellspacing="0" cellpadding="0" class="toolTip"><tr><td bgcolor="' + fg + '">' +
                                  '<table border="0" cellspacing="1" cellpadding="0"<tr><td bgcolor="' + bg + '">'+
                                  '<font face="sans-serif" color="' + fg + '" size="-2">' + msg +
                                  '</font></td></tr></table>'+
                                  '</td></tr></table>';
   if(is_nav4)
    {
      toolTipSTYLE.document.write(content);
      toolTipSTYLE.document.close();
      toolTipSTYLE.visibility = "visible";
    }

    else if(is_ie || is_nav6up)
    {
      document.getElementById("toolTipLayer").innerHTML = content;
      toolTipSTYLE.display='block'
    }
  }
}

s = '<table width="100%" cellspacing="2" cellpadding="0" border="0">';
s += '<tr><td><img src="http://upload.wikimedia.org/wikipedia/meta/2/2a/Nohat-logo-nowords-bgwhite-200px.jpg" border="0"/> </td><td valign="top">WikiPedia</td></tr>';
s += '<tr><td colspan="2" class="Text"><hr/>this is a test for simple tooltip. <br/>You can add text and images to the tooltip</td></tr>';
s += '</table>'

function show(){
        toolTip(s)
}

2009年5月10日 星期日

Youtube 轉成未壓縮的 AVI

請先下載:

1. 解壓縮軟體:
http://www.7-zip.org/
2. 轉檔軟體:
http://ffdshow.faireal.net/mirror/ffmpeg/ffmpeg.rev9079.7z
3. Download 軟體:
http://roxsu.tw.googlepages.com/mydownload.7z

用7-Zip 將2,3 軟體解壓縮到同一目錄下

在該目錄找到程式 MyDownloader.App.exe

並執行之.

附註:
1. 請先自行下載並安裝Microsoft .Net FrameWork 2.0 或以後版本.
2. 執行時記得勾選 "下載完轉成AVI"及輸入"儲存路徑".

2009年5月2日 星期六

2009年2月11日 星期三

Crystal Report: export to html

Export to html or PDF or Excel file:

<code>

Private Sub Print(ByVal strRpt As String)
    Dim reportDoc As New ReportDocument
    lblDBErrorMessage.Text = ""
    Dim rpt_ds As DataSet = GetRptDS()
    If lblDBErrorMessage.Text <> "" Then
        Exit Sub
    End If
    reportDoc.Load(Server.MapPath("demorpt.rpt"))
    reportDoc.SetDataSource(rpt_ds)
    Select Case strRpt
    Case "HTML"
        Dim htmlformat As New HTMLFormatOptions
        reportDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
        reportDoc.ExportOptions.ExportFormatType = ExportFormatType.HTML40
        htmlformat.HTMLBaseFolderName = Server.MapPath("../printemp/")
        '放在/printemp/之下,它會自動產生demorpt資料夾
        '和其他的匯出不一樣要設定htmlformat
        htmlformat.HTMLFileName = "demo.htm"
        reportDoc.ExportOptions.FormatOptions = htmlformat
        reportDoc.Export()
        Dim htmurl As String = "../printemp/demorpt/demo.htm"
        Response.Redirect(htmurl)
    Case "PDF"
        Dim objFile As New DiskFileDestinationOptions
        reportDoc.ExportOptions.DestinationOptions = objFile
        objFile.DiskFileName = Server.MapPath("../printemp/demo.pdf")
        With reportDoc.ExportOptions
            .ExportDestinationType = ExportDestinationType.DiskFile
            .ExportFormatType = ExportFormatType.PortableDocFormat
            .DestinationOptions = objFile
        End With
        reportDoc.Export()
        Dim xlsurl As String = "../printemp/demo.pdf"
        Response.Redirect(xlsurl)
    Case "Excel"
        Dim objFile As New DiskFileDestinationOptions
        Dim CrFormatTypeOptions As New ExcelFormatOptions                       
        With CrFormatTypeOptions                                      
            .ExcelTabHasColumnHeadings = True                        
            .ExcelAreaType = AreaSectionKind.PageHeader              
            .ExcelUseConstantColumnWidth = False                   
        End With                                                       
        reportDoc.ExportOptions.DestinationOptions = objFile
        objFile.DiskFileName = Server.MapPath("../printemp/demo.xls")
        With reportDoc.ExportOptions
            .ExportDestinationType = ExportDestinationType.DiskFile
            .ExportFormatType = ExportFormatType.Excel
            .DestinationOptions = objFile
            .FormatOptions = CrFormatTypeOptions           
        End With
        reportDoc.Export()
        Dim xlsurl As String = "../printemp/demo.xls"
        Response.Redirect(xlsurl)
    End Select
End Sub

</code>

2009年1月10日 星期六

Email Datagrid as mailbody

下面例子將Datagrid當Email內容寄送:


Dim objMail As New MailMessage
objMail.BodyEncoding = Encoding.UTF8
objMail.Subject = "Email Subject"
objMail.From = "email@address"
SmtpMail.SmtpServer = "xxx.xxx.xxx.xxx"
objMail.BodyFormat = MailFormat.Html
objMail.To = "email@address"
Dim sw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(sw)
load_grid() ' bind data to Datagrid_mail
Datagrid_mail.Visible = True
Datagrid_mail.RenderControl(hw)
objMail.Body = "Hello:" + "<br>" + "<br>" + sw.ToString()
Datagrid_mail.Visible = False
Try
SmtpMail.Send(objMail)
Catch ex As Exception
lblDBErrorMessage.Text = "Error!"
End Try


動態產生 datagrid Columns

要動態產生datagrid 之columns 必須先建一個介面:

Public Class tempcheck
Implements ITemplate

Private plbnID As String

Public Sub New(ByVal lbnID As String)
plbnID = lbnID
End Sub

Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim lbn As New CheckBox
lbn.ID = plbnID
lbn.Text = ""
lbn.Visible = True
AddHandler lbn.DataBinding, AddressOf TemplateControl_DataBinding
container.Controls.Add(lbn)
End Sub

Private Sub TemplateControl_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lc As CheckBox
lc = CType(sender, CheckBox)
Dim container As DataGridItem
container = CType(lc.NamingContainer, DataGridItem)
lc.Checked = DataBinder.Eval(container.DataItem, plbnID)
End Sub

End Class

再datagrid Bind資料前定義column:

先將column資料讀入dataset: ds_bar

再分別新增datagrid : grdResults.Columns

及mytable.Columns

...

Dim myTable As DataTable = New DataTable
myTable.TableName = "auth"
myTable.Columns.Add(New DataColumn("my_sno", GetType(Integer)))
myTable.Columns.Add(New DataColumn("my_co", GetType(String)))
myTable.Columns.Add(New DataColumn("my_name", GetType(String)))
Dim v_bn As String
Dim i As Integer
Dim v_col As TemplateColumn
For i = 0 To ds_bar.Tables(0).Rows.Count - 1
v_col = New TemplateColumn
v_bn = ds_bar.Tables(0).Rows(i).Item("baritemname").ToString.Trim.Remove(0, 2)
v_col.HeaderText = v_bn
v_col.ItemTemplate = New tempcheck("my_bt_" + v_bn)
grdResults.Columns.Add(v_col)
myTable.Columns.Add(New DataColumn("my_bt_" + v_bn, GetType(Boolean)))
Next

......

最後再將myTable bind 到datagrid:

Dim dvwGrid As DataView = myTable.DefaultView
grdResults.DataSource = dvwGrid
Try
grdResults.DataBind()
Catch
grdResults.CurrentPageIndex = 0
grdResults.DataBind()
End Try


而資料的取得要用Request.Form:


For I = 0 To grdResults.Items.Count - 1
For jj = 0 To ds_bar.Tables(0).Rows.Count - 1
v_bn = ds_bar.Tables(0).Rows(jj).Item("baritemname").ToString.Trim.Remove(0, 2)
v_btn = "my_bt_" + v_bn
v_uid = grdResults.Items(I).UniqueID + ":"
v_chk = Request.Form(v_uid + v_btn)
.....