[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int wndproc);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public const int GWL_STYLE = -16;
public const int WS_DISABLED = 0x8000000;
public static void SetControlEnabled(Control c, bool enabled)
{
if (enabled)
{ SetWindowLong(c.Handle, GWL_STYLE, (~WS_DISABLED) & GetWindowLong(c.Handle, GWL_STYLE)); }
else
{ SetWindowLong(c.Handle, GWL_STYLE, WS_DISABLED | GetWindowLong(c.Handle, GWL_STYLE)); }
}
void SetControlEnableState(Control c, bool enabled)
{
SetControlEnabled(c,enabled);
c.ForeColor=Color.Dark;
}
2009年12月21日 星期一
2009年11月22日 星期日
Windows XP 顯示桌面捷徑
首先開啟記事本
開始-->程式集-->附屬應用程式-->記事本
(建議不要在桌面上直接按右鍵新增文字文件
因為這樣一開始它就會預設檔案格式為*.txt
之後還要去改格式一次喔)
key入以下的文字:
[Shell]
Command=2
IconFile=explorer.exe,3
[Taskbar]
Command=ToggleDesktop
然後存檔
存放路徑:
C:\Documents and Settings\你的名字\Application Data\Microsoft\Internet Explorer\Quick Launch
檔名:顯示桌面.scf
存檔類型:所有檔案
編碼:ANSI
(如果你的電腦是只有你一個人使用
那麼存放路徑可以直接key成
C:\Documents and Settings\Administrator\Application Data\Microsoft\Internet Explorer\Quick Launch
開始-->程式集-->附屬應用程式-->記事本
(建議不要在桌面上直接按右鍵新增文字文件
因為這樣一開始它就會預設檔案格式為*.txt
之後還要去改格式一次喔)
key入以下的文字:
[Shell]
Command=2
IconFile=explorer.exe,3
[Taskbar]
Command=ToggleDesktop
然後存檔
存放路徑:
C:\Documents and Settings\你的名字\Application Data\Microsoft\Internet Explorer\Quick Launch
檔名:顯示桌面.scf
存檔類型:所有檔案
編碼:ANSI
(如果你的電腦是只有你一個人使用
那麼存放路徑可以直接key成
C:\Documents and Settings\Administrator\Application Data\Microsoft\Internet Explorer\Quick Launch
2009年11月11日 星期三
多筆資料欄合併SQL Example
DECLARE @table TABLE (id nvarchar(4), memo nvarchar(4))
INSERT INTO @table (id, memo)VALUES ('1', 'm1');
INSERT INTO @table (id, memo)VALUES ('1', 'm2');
INSERT INTO @table (id, memo)VALUES ('2', 'm3');
INSERT INTO @table (id, memo)VALUES ('2', 'm4');
INSERT INTO @table (id, memo)VALUES ('3', 'm5');
INSERT INTO @table (id, memo)VALUES ('3', 'm6');
SELECT T1.id,
(
SELECT memo + ''
FROM @table T2
WHERE T2.id = T1.id
ORDER BY memo
FOR XML PATH('')
) AS memo
FROM @table T1
GROUP BY id
INSERT INTO @table (id, memo)VALUES ('1', 'm1');
INSERT INTO @table (id, memo)VALUES ('1', 'm2');
INSERT INTO @table (id, memo)VALUES ('2', 'm3');
INSERT INTO @table (id, memo)VALUES ('2', 'm4');
INSERT INTO @table (id, memo)VALUES ('3', 'm5');
INSERT INTO @table (id, memo)VALUES ('3', 'm6');
SELECT T1.id,
(
SELECT memo + ''
FROM @table T2
WHERE T2.id = T1.id
ORDER BY memo
FOR XML PATH('')
) AS memo
FROM @table T1
GROUP BY id
2009年11月10日 星期二
MS SQL Dump Restore SqlScript
use master
go
alter database mydb set single_user with rollback immediate
go
restore database mydb
from disk=』D:PATHTODBBAKmydb.full'
with recovery
go
go
alter database mydb set single_user with rollback immediate
go
restore database mydb
from disk=』D:PATHTODBBAKmydb.full'
with recovery
go
2009年11月3日 星期二
開心農場新6.5小時賺錢法
開心農場新6.5小時賺錢法
種植美粒果葡萄袖
生長時程 12 + 3 + 1 + 5 +5 =26小時
第一季使用化肥 6.5 + 6.5 + 1 + 6.5 +6.5 = 6.5小時(種植時數)
第二~四季 6.5 + 6.5 = 0 小時(種植時數)
淨利 (34476 * 4) - 6125 - 10100 = 121679
話說回來....賺那麼多錢要做啥....還不是一塊地都買不起>"<
種植美粒果葡萄袖
生長時程 12 + 3 + 1 + 5 +5 =26小時
第一季使用化肥 6.5 + 6.5 + 1 + 6.5 +6.5 = 6.5小時(種植時數)
第二~四季 6.5 + 6.5 = 0 小時(種植時數)
淨利 (34476 * 4) - 6125 - 10100 = 121679
話說回來....賺那麼多錢要做啥....還不是一塊地都買不起>"<
2009年10月29日 星期四
MS SQL Paging 語法
轉錄自PTT
CREATE PROCEDURE sp_Paging
@tblName varchar(255) ,
@strGetFields varchar(1000) = '*',
@fldName varchar(255)='',
@pageSize int = 10,
@pageIndex int = 1,
@recordCount int = 0 output,
@pageCount int = 0 output,
@orderType int = 0,
@strWhere varchar(1500) = ''
AS
declare @strSQL nvarchar(3000)
declare @strTmp varchar(110)
declare @strOrder varchar(400)
begin
if @strWhere !=''
set @strSQL = 'select @recordCount = count(*) from ' + @tblName + ' where '+@strWhere
else
set @strSQL = 'select @recordCount = count(*) from ' + @tblName
end
exec sp_executesql @strSQL,N'@recordCount int out ',@recordCount out
if @recordCount % @pageSize = 0
set @pageCount = @recordCount / @pageSize
else
set @pageCount = @recordCount / @pageSize + 1
--計算出記錄是總數和求出總共的頁數
begin
if @orderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by ' + @fldName +' desc'
--如果@orderType不是0﹐就執行降序﹐這句很重要﹗
end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by ' + @fldName +' asc'
end
if @pageIndex = 1
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from ' + @tblName + ' where ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '+ @tblName + ' '+ @strOrder
end
else
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + '' + @strTmp + '('
+ substring(@fldName, charindex('.',@fldName)+1, len(@fldName)) + ') from (select top ' + str((@pageIndex-1)*@pageSize) + ' '
+ @fldName + ' from ' + @tblName + ' where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + '' + @strTmp + '('
+ substring(@fldName, charindex('.',@fldName)+1, len(@fldName)) + ') from (select top ' + str((@pageIndex-1)*@pageSize) + ' '
+ @fldName + ' from ' + @tblName + '' + @strOrder + ') as tblTmp)'
+ @strOrder
end
end
--print @strSQL
exec sp_executesql @strSQL
GO
CREATE PROCEDURE sp_Paging
@tblName varchar(255) ,
@strGetFields varchar(1000) = '*',
@fldName varchar(255)='',
@pageSize int = 10,
@pageIndex int = 1,
@recordCount int = 0 output,
@pageCount int = 0 output,
@orderType int = 0,
@strWhere varchar(1500) = ''
AS
declare @strSQL nvarchar(3000)
declare @strTmp varchar(110)
declare @strOrder varchar(400)
begin
if @strWhere !=''
set @strSQL = 'select @recordCount = count(*) from ' + @tblName + ' where '+@strWhere
else
set @strSQL = 'select @recordCount = count(*) from ' + @tblName
end
exec sp_executesql @strSQL,N'@recordCount int out ',@recordCount out
if @recordCount % @pageSize = 0
set @pageCount = @recordCount / @pageSize
else
set @pageCount = @recordCount / @pageSize + 1
--計算出記錄是總數和求出總共的頁數
begin
if @orderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by ' + @fldName +' desc'
--如果@orderType不是0﹐就執行降序﹐這句很重要﹗
end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by ' + @fldName +' asc'
end
if @pageIndex = 1
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from ' + @tblName + ' where ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '+ @tblName + ' '+ @strOrder
end
else
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + '' + @strTmp + '('
+ substring(@fldName, charindex('.',@fldName)+1, len(@fldName)) + ') from (select top ' + str((@pageIndex-1)*@pageSize) + ' '
+ @fldName + ' from ' + @tblName + ' where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@pageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + '' + @strTmp + '('
+ substring(@fldName, charindex('.',@fldName)+1, len(@fldName)) + ') from (select top ' + str((@pageIndex-1)*@pageSize) + ' '
+ @fldName + ' from ' + @tblName + '' + @strOrder + ') as tblTmp)'
+ @strOrder
end
end
--print @strSQL
exec sp_executesql @strSQL
GO
2009年10月27日 星期二
2009年10月26日 星期一
Windows XP 遠端桌面修改Port
本文說明如何變更遠端桌面聽候的連接埠。'
本文將告訴您如何變更「遠端桌面」用戶端所連線的連接埠號碼。如果遠端電腦已經變更「終端機服務」或「遠端桌面」連線的「聽候」連接埠的預設連接埠,您就可能需要執行此項操作。預設連接埠為 3389。
http://support.microsoft.com/kb/304304/
- 啟動「登錄編輯程式」。
- 找出並按一下下列登錄子機碼:HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber
- 在 [編輯] 功能表上,按一下 [修改],再按一下 [十進位]。
- 輸入新的連接埠編號,然後按一下 [確定]。
- 結束「登錄編輯器」。
本文將告訴您如何變更「遠端桌面」用戶端所連線的連接埠號碼。如果遠端電腦已經變更「終端機服務」或「遠端桌面」連線的「聽候」連接埠的預設連接埠,您就可能需要執行此項操作。預設連接埠為 3389。
- 按一下 [開始],依序按一下 [所有程式],指向 [附屬應用程式],指向 [通訊],再按一下 [遠端桌面連線]。
- 在 [電腦] 方塊中,輸入您要連線的電腦名稱或 IP 位址,之後跟隨冒號 (:),以及要使用的連接埠號碼。
例如,如果要連線到名為 MyXPPro 電腦上的連接埠 3390,請輸入下列資訊:MyXPPro:3390如果要在 IP 位址為 10.10.10.1 的電腦上,連線到連接埠 3391,請輸入下列資訊:10.10.10.1:3391 - 按一下 [連線]。
http://support.microsoft.com/kb/304304/
Windows XP 自動登入設定
- 按「開始」,到執行,輸入:
control userpasswords2
- 按確定。
- 這時會帶出管理使用者帳號的畫面,在「使用者」這一頁面,不勾 :必須輸入使用者名稱和密碼,才能使用這台電腦,按套用。
- 此時會出現要求輸入密碼的畫面,請輸入你要自動登入的帳號與密碼,Windows XP就會以該組帳號作為自動登入的帳號。
若要恢復到原本可以選擇帳號的設定,與以上步驟都相同,只是勾起「必須輸入使用者名稱和密碼,才能使用這台電腦」
2009年10月21日 星期三
2009年10月16日 星期五
VS 2005 Winform 輸入法全型切換錯誤問題
首先在專案中新增一個Class
Public Class ImeForm
Inherits System.Windows.Forms.Form
Private Declare Function ImmGetContext Lib "imm32.dll" (ByVal hwnd As Integer) As Integer
Private Declare Function ImmGetConversionStatus Lib "imm32.dll" (ByVal himc As Integer, ByRef lpdw As Integer, ByRef lpdw2 As Integer) As Integer
Private Declare Function ImmSimulateHotKey Lib "imm32.dll" (ByVal hwnd As Integer, ByVal dw As Integer) As Integer
Private Sub Form_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
For Each objCtl As Control In Me.Controls
AddHandler objCtl.GotFocus, AddressOf ControlIME
Next
End Sub
Private Sub Form_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
ControlIME(Me, Nothing)
End Sub
Private Shared Sub ControlIME(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lngStatus As Long, lngSt As Long, h As IntPtr = sender.Handle
ImmGetConversionStatus(ImmGetContext(h), lngStatus, lngSt)
If lngStatus = 9 Then ImmSimulateHotKey(h, 113)
End Sub
End Class
繼承ImeForm
Public Class ControlCenter
Inherits ImeForm
2009年10月12日 星期一
2009年9月28日 星期一
全形/半形 互換
- '半形轉全形
- Public Function ToWchr(ByRef data As String) As String
- Dim sb As New StringBuilder
- Dim ascii As Integer = 0
-
- For Each c As Char In data.ToCharArray()
- ascii = Convert.ToInt32(c)
- If ascii = 32 Then
- sb.Append(Convert.ToChar(12288))
- Else
- sb.Append(Convert.ToChar(ascii + IIf(ascii <>
- End If
- Next
-
- Return sb.ToString
- End Function
-
- ' 全形 轉 半形
- Public Function ToNchr(ByRef data As String) As String
- Dim sb As New StringBuilder
- Dim ascii As Integer = 0
-
- For Each c As Char In data.Replace("〔", "[").Replace("〕", "]").Replace("'", "'").ToCharArray()
- ascii = Convert.ToInt32(c)
- If ascii = 12288 Then
- sb.Append(Convert.ToChar(32))
- Else
- If ascii > 65280 And ascii <>Then
- sb.Append(Convert.ToChar(ascii - 65248))
- Else
- sb.Append(Convert.ToChar(ascii))
- End If
- End If
- Next
-
- Return sb.ToString
- End Function
2009年9月21日 星期一
Winform 設定輸入法
如何改變輸入法
//1.設定輸入法,依comboBox1選擇
InputLanguage MyInput = InputLanguage.InstalledInputLanguages[this.comboBox1.SelectedIndex];
//2.設定輸入法
InputLanguage.CurrentInputLanguage = MyInput; 完整程式碼 private void Form1_Load(object sender, EventArgs e)
{
//清除
this.listBox1.Items.Clear();
//1.收集系統已安裝的輸入法
InputLanguageCollection myInput = InputLanguage.InstalledInputLanguages;
//2.列舉輸入法
foreach (InputLanguage input in myInput)
{
//加入控制項
this.comboBox1.Items.Add(input.LayoutName);
}
//3.取得目前輸入法
InputLanguage CurrentInput = InputLanguage.CurrentInputLanguage;
listBox1.Items.Add("目前輸入法名稱為: " + "\t" + CurrentInput.LayoutName);
//4.取得輸入法區域
listBox1.Items.Add("目前輸入法文化特性為: " + "\t" + CurrentInput.Culture.DisplayName);
//5.取得預設的輸入法
InputLanguage DefaultInput = InputLanguage.DefaultInputLanguage;
listBox1.Items.Add("預設輸入法文化特性為: " + "\t" + DefaultInput.LayoutName);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//清除
this.listBox1.Items.Clear();
//1.設定輸入法,依comboBox1選擇
InputLanguage MyInput = InputLanguage.InstalledInputLanguages[this.comboBox1.SelectedIndex];
//2.設定輸入法
InputLanguage.CurrentInputLanguage = MyInput;
//3.取得目前輸入訊息
InputLanguage CurrentInput = InputLanguage.CurrentInputLanguage;
listBox1.Items.Add("目前輸入法名稱為: " + "\t" + CurrentInput.LayoutName);
//4.取得輸入法區域
listBox1.Items.Add("目前輸入法文化特性為: " + "\t" + CurrentInput.Culture.DisplayName);
//5.取得預設輸入法
InputLanguage DefaultInput = InputLanguage.DefaultInputLanguage;
listBox1.Items.Add("預設輸入法文化特性為: " + "\t" + DefaultInput.LayoutName);
}
2009年9月8日 星期二
C# Textbox Enable 時改變字體及背景顏色
//重寫OnEnabledChanged
protected override void OnEnabledChanged(EventArgs e)
{
if (Enabled==false){
SetStyle(ControlStyles.UserPaint,true);
}
else{
SetStyle(ControlStyles.UserPaint,false);
}
base.OnEnabledChanged(e);
}
//重寫OnPaint
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (Enabled==false){
pe.Graphics.FillRectangle(new SolidBrush(SystemColors.ControlLight),
pe.ClipRectangle);
//文字描畫
int x=0,y=0;
Size s = pe.Graphics.MeasureString(Text,Font).ToSize();
x=Width-s.Width;
y=(Height-s.Height)/2;
pe.Graphics.DrawString(this.Text, this.Font, Brushes.Black , x, y);
}
}
protected override void OnEnabledChanged(EventArgs e)
{
if (Enabled==false){
SetStyle(ControlStyles.UserPaint,true);
}
else{
SetStyle(ControlStyles.UserPaint,false);
}
base.OnEnabledChanged(e);
}
//重寫OnPaint
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (Enabled==false){
pe.Graphics.FillRectangle(new SolidBrush(SystemColors.ControlLight),
pe.ClipRectangle);
//文字描畫
int x=0,y=0;
Size s = pe.Graphics.MeasureString(Text,Font).ToSize();
x=Width-s.Width;
y=(Height-s.Height)/2;
pe.Graphics.DrawString(this.Text, this.Font, Brushes.Black , x, y);
}
}
2009年9月7日 星期一
How to find objects in Generics with List.Find() method
How to find objects in Generics with List.Find() method
I've been looking for help on how to find objects in Generics with List.Find() method .... and ... take a look what I have found.
In the follow example, I created a simple class:
public class Person
{
private int _id;
private string _name;
public int ID { get{ return _id;} set{ _id = value;}}
public int Name { get{ return _name;} set{ _name= value;}}
public Person(int id, string name)
{
_id = id;
_name = name;
}
}
In the example, there's a simple class with two private attributes. Now we're going to create a typed List of this object and take advantage of the Find() method
public void CreateAndSearchList()
{
//create and fill the collection
List myList = new List();
myList.Add(new Person(1, "AndreySanches"));
myList.Add(new Person(2, "AlexandreTarifa"));
myList.Add(new Person(3, "EmersonFacunte"));
//find a specific object
Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });
}
I've been looking for help on how to find objects in Generics with List.Find() method .... and ... take a look what I have found.
In the follow example, I created a simple class:
public class Person
{
private int _id;
private string _name;
public int ID { get{ return _id;} set{ _id = value;}}
public int Name { get{ return _name;} set{ _name= value;}}
public Person(int id, string name)
{
_id = id;
_name = name;
}
}
In the example, there's a simple class with two private attributes. Now we're going to create a typed List of this object and take advantage of the Find() method
public void CreateAndSearchList()
{
//create and fill the collection
List
myList.Add(new Person(1, "AndreySanches"));
myList.Add(new Person(2, "AlexandreTarifa"));
myList.Add(new Person(3, "EmersonFacunte"));
//find a specific object
Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });
}
2009年8月19日 星期三
DataGridView 顯示行號
#region dataGridView1顯示行號
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
#endregion
在dataGridView1的RowPostPaint事件中,選擇dataGridView1_RowPostPaint函數
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
#endregion
在dataGridView1的RowPostPaint事件中,選擇dataGridView1_RowPostPaint函數
2009年8月18日 星期二
動態修改ComboBox選項寬度
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidth:0;
int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
2009年8月12日 星期三
ReportViewer 切換至預覽列印模式
1. 用ReportView的SetDisplayMode方法 將顯示模式切換至PrintLayout(列印預覽);
2. 在 [列印預覽] 模式中,[縮放] 下拉式清單預設選項是 [整頁]。因此切換ZoomMode屬性為Percent,
並設定ZoomPercent屬性為100;
程式碼如下:
using Microsoft.Reporting.WinForms;(引命名空間)
private void CouponPrint_Load(object sender, EventArgs e)
{
{
//以列印模式顯示
this.reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
this.reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
//切換縮放方式為百分比 - 100%
this.reportViewer1.ZoomMode = ZoomMode.Percent;
this.reportViewer1.ZoomPercent = 100;
this.reportViewer1.ZoomMode = ZoomMode.Percent;
this.reportViewer1.ZoomPercent = 100;
}
2009年8月4日 星期二
Report View 傳入參數
Dim AR(2) As ReportParameter
AR(0) = New ReportParameter("REPORT_TITLE", "報表標題")
AR(1) = New ReportParameter("Para1", "1")
AR(2) = New ReportParameter("Para2", "2")
ReportViewer1.LocalReport.SetParameters(AR)
動態修改RDLC的資料來源
dim cnn As New SqlConnection(ConfigurationManager.ConnectionStrings("AdventureWorksConnectionString").ConnectionString)
3 Dim cmd As New SqlCommand("SELECT * FROM HumanResources.Employee WHERE MaritalStatus='S'", cnn)
4 Dim da As New SqlDataAdapter(cmd)
5 '將動態Select出來的資料填入Datatable當資料來源
6 Dim dt As New DataTable
7 da.Fill(dt)
8 '將ReportViewer1的DataSources集合清除
9 ReportViewer1.LocalReport.DataSources.Clear()
10 '然後重新新增一個名稱為"AdventureWorksDataSet_Employee"的ReportDataSource給ReportViewer1
11 ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("AdventureWorksDataSet_Employee", dt))
12 ReportViewer1.LocalReport.Refresh()
3 Dim cmd As New SqlCommand("SELECT * FROM HumanResources.Employee WHERE MaritalStatus='S'", cnn)
4 Dim da As New SqlDataAdapter(cmd)
5 '將動態Select出來的資料填入Datatable當資料來源
6 Dim dt As New DataTable
7 da.Fill(dt)
8 '將ReportViewer1的DataSources集合清除
9 ReportViewer1.LocalReport.DataSources.Clear()
10 '然後重新新增一個名稱為"AdventureWorksDataSet_Employee"的ReportDataSource給ReportViewer1
11 ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("AdventureWorksDataSet_Employee", dt))
12 ReportViewer1.LocalReport.Refresh()
2009年7月27日 星期一
DataGridView中被表示的TextBox的AutoComplete有效
DataGridView中被表示的TextBox的AutoComplete有效
注意:DataGridView控件是從.NET Framework 2.0版本開始追加的。
在DataGridView中被表示TextBox的AutoComplete有效的方法,如果對「取得在DataGridView中表示的TextBox」中所介紹的方法理解的話,就相當簡單。就是對取得的TextBox的AutoCompleteMode屬性進行變更即可。
下面的例子是文字型的"Column1"列中表示的TextBox增加AutoComplete的代碼。
[VB.NET]
Dim autoCompleteSource As New AutoCompleteStringCollection()
'EditingControlShowing事件處理器
Private Sub DataGridView1_EditingControlShowing( _
ByVal sender As Object, _
ByVal e As DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
Dim dgv As DataGridView = CType(sender, DataGridView)
If TypeOf e.Control Is TextBox Then
'取得了被表示的TextBox
Dim tb As TextBox = CType(e.Control, TextBox)
'檢測對應列
If dgv.CurrentCell.OwningColumn.Name = "Column1" Then
'AutoComplete有效
tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend
tb.AutoCompleteSource = _
Windows.Forms.AutoCompleteSource.CustomSource
tb.AutoCompleteCustomSource = Me.autoCompleteSource
Else
'AutoComplete無效
tb.AutoCompleteMode = AutoCompleteMode.None
End If
End If
End Sub
'DataSourceChanged事件處理器
Private Sub DataGridView1_DataSourceChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles DataGridView1.DataSourceChanged
Dim dgv As DataGridView = CType(sender, DataGridView)
'AutoComplete的List初始化
Me.autoCompleteSource.Clear()
'向List追加DataGridView內的數據
Dim r As DataGridViewRow
For Each r In dgv.Rows
'取得單元格的值
Dim val As String = r.Cells("Column1").Value
If Not String.IsNullOrEmpty(val) AndAlso _
Not Me.autoCompleteSource.Contains(val) Then
'向AutoComplete的List追加
autoCompleteSource.Add(val)
End If
Next r
End Sub
'CellValueChanged事件處理器
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
Dim dgv As DataGridView = CType(sender, DataGridView)
'檢測對應列
If dgv.Columns(e.ColumnIndex).Name = "Column1" Then
'取得單元格的值
Dim val As String = dgv(e.ColumnIndex, e.RowIndex).Value
If Not String.IsNullOrEmpty(val) AndAlso _
Not Me.autoCompleteSource.Contains(val) Then
'向AutoComplete的List追加
autoCompleteSource.Add(val)
End If
End If
End Sub
[C#]
AutoCompleteStringCollection autoCompleteSource =
new AutoCompleteStringCollection();
//EditingControlShowing事件處理器
private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.Control is TextBox)
{
//取得了被表示的TextBox
TextBox tb = (TextBox)e.Control;
//檢測對應列
if (dgv.CurrentCell.OwningColumn.Name == "Column1")
{
// AutoComplete有效
tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
tb.AutoCompleteCustomSource = this.autoCompleteSource;
}
else
{
// AutoComplete無效
tb.AutoCompleteMode = AutoCompleteMode.None;
}
}
}
//DataSourceChanged事件處理器
private void DataGridView1_DataSourceChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// AutoComplete的List初始化
this.autoCompleteSource.Clear();
//向List追加DataGridView內的數據
foreach (DataGridViewRow r in dgv.Rows)
{
//取得單元格的值
string val = r.Cells["Column1"].Value as string;
if (!string.IsNullOrEmpty(val) &&
!this.autoCompleteSource.Contains(val))
{
//向AutoComplete的List追加
autoCompleteSource.Add(val);
}
}
}
//CellValueChanged事件處理器
private void DataGridView1_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//檢測對應列
if (dgv.Columns[e.ColumnIndex].Name == "Column1")
{
//取得單元格的值
string val = dgv[e.ColumnIndex, e.RowIndex].Value as string;
if (!string.IsNullOrEmpty(val) &&
!this.autoCompleteSource.Contains(val))
{
//向AutoComplete的List追加
autoCompleteSource.Add(val);
}
}
}
2009年7月26日 星期日
SQL Server 2005 Express Backup Script
SQL 2005 (and Express) Backup Script
After the last few years of finding some good ideas and tweaking my script I wanted to let everyone use it. If you want.
Here are some directions on how to use it.
1) Create a text file and name it Backup_All_Databases.sql (or what ever you want).
2) Paste the below script in it:
3) Open scheduler and create a new task that calls the below command line:
Note: I also made a batch file that had the same command line but added a pause so I can test it before the scheduler runs it.
EXAMPLE:
4) Just run it every night in a scheduler and you are done.
Clean up Old Backup Files.
If you are running Windows Server 2003 you can also run a command utility to delete any files older then x number of days. This helps keep it cleaned up. Just paste this in a batch file and schedule the batch file.
This will also work on SQL Express
After the last few years of finding some good ideas and tweaking my script I wanted to let everyone use it. If you want.
Here are some directions on how to use it.
1) Create a text file and name it Backup_All_Databases.sql (or what ever you want).
2) Paste the below script in it:
DECLARE @BackupFile varchar(255), @DB varchar(30), @Description varchar(255), @LogFile varchar(50) DECLARE @Name varchar(30), @MediaName varchar(30), @BackupDirectory nvarchar(200) SET @BackupDirectory = 'C:\Backuped_SQL_DB\' --Add a list of all databases you don't want to backup to this. DECLARE Database_CURSOR CURSOR FOR SELECT name FROM sysdatabases WHERE name <> 'tempdb' AND name <> 'model' AND name <> 'Northwind' OPEN Database_Cursor FETCH next FROM Database_CURSOR INTO @DB WHILE @@fetch_status = 0 BEGIN SET @Name = @DB + '( Daily BACKUP )' SET @MediaName = @DB + '_Dump' + CONVERT(varchar, CURRENT_TIMESTAMP , 112) SET @BackupFile = @BackupDirectory + + @DB + '_' + 'Full' + '_' + CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak' SET @Description = 'Normal' + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' IF (SELECT COUNT(*) FROM msdb.dbo.backupset WHERE database_name = @DB) > 0 OR @DB = 'master' BEGIN SET @BackupFile = @BackupDirectory + @DB + '_' + 'Full' + '_' + CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak' --SET some more pretty stuff for sql server. SET @Description = 'Full' + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' END ELSE BEGIN SET @BackupFile = @BackupDirectory + @DB + '_' + 'Full' + '_' + CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak' --SET some more pretty stuff for sql server. SET @Description = 'Full' + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' END BACKUP DATABASE @DB TO DISK = @BackupFile WITH NAME = @Name, DESCRIPTION = @Description , MEDIANAME = @MediaName, MEDIADESCRIPTION = @Description , STATS = 10 FETCH next FROM Database_CURSOR INTO @DB END CLOSE Database_Cursor DEALLOCATE Database_Cursor
3) Open scheduler and create a new task that calls the below command line:
Code:
sqlcmd -S . -i "C:\Backups\BackupSettings\Backup_All_Databases.sql"
EXAMPLE:
Code:
sqlcmd -S . -i "C:\Backups\BackupSettings\Backup_All_Databases.sql" pause
Clean up Old Backup Files.
If you are running Windows Server 2003 you can also run a command utility to delete any files older then x number of days. This helps keep it cleaned up. Just paste this in a batch file and schedule the batch file.
Code:
echo on rem First Delete old SQL Backup Files FORFILES /p C:\Backuped_SQL_DB /s /m *.* /d -3 /c "CMD /C del /Q @FILE" rem pause
2009年7月25日 星期六
MaskedTextbox TextMaskFormat
當 TextMaskFormat 為 IncludeLiterals 的話...則取用 Text 屬性得到 "0968-12 - " (包含 常值)
ExcludePromptAndLiterals 則得到 "096812" (不包含 提示字元 與 常值 )
IncludePrompt 則得到 "096812____" (包含 提示字元)
IncludePromptAndLiterals 則得到 "0968-12_-____" (包含 提示字元 與 常值)
而 TextMaskFormat 與 CutCopyMaskFormt 分別在於....
TextMaskFormat : 用程式取用 Text 屬性得到的結果CutCopyMaskFormt : 利用 複製 or 剪下得到的結果
2009年7月20日 星期一
SQL 取得相關資料表及欄位說明
= SQL Server
SQL Command:
1.取得資料庫表單數量
select count(*) as totaltablenumber
from sysobjects
where xtype = 'U';
2.取得資料表名稱(tablename)及欄位數量(columnnumber)
select name as tablename, info as columnnumber
from sysobjects
where xtype = 'U';
3.取得某一資料表內所有欄位名稱
select b.name
from sysobjects as a, syscolumns as b
where a.xtype = 'U' and a.id = b.id and a.name='資料表單名稱';
3.1 取得某一資料表內所有欄位名稱
EXEC sp_columns 表單名稱
Store Procedure:
資料庫中所有資料表:透過內定的Stored Procedure sp_tables
sp_columns @TableName
取得欄位說明、備註(Extended Property):這個是透過Sql內定的Function來處理
sp_pkeys @TableName
SQL Command:
1.取得資料庫表單數量
select count(*) as totaltablenumber
from sysobjects
where xtype = 'U';
2.取得資料表名稱(tablename)及欄位數量(columnnumber)
select name as tablename, info as columnnumber
from sysobjects
where xtype = 'U';
3.取得某一資料表內所有欄位名稱
select b.name
from sysobjects as a, syscolumns as b
where a.xtype = 'U' and a.id = b.id and a.name='資料表單名稱';
3.1 取得某一資料表內所有欄位名稱
EXEC sp_columns 表單名稱
Store Procedure:
資料庫中所有資料表:透過內定的Stored Procedure sp_tables
- EXEC sp_tables
- @table_name = '%',
- @table_owner = 'dbo',
- @table_qualifier = @DBName;
sp_columns @TableName
取得欄位說明、備註(Extended Property):這個是透過Sql內定的Function來處理
- SELECT *
- FROM ::fn_listextendedproperty(NULL, 'user', 'dbo', 'table', @TableName, 'column', default)
sp_pkeys @TableName
2009年7月17日 星期五
Windform DataGridView 搭配DateTimePicker使用
1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Text;
7. using System.Windows.Forms;
8.
9. namespace DataGridViewDateTimePicker
10. {
11. public partial class MainForm : Form
12. {
13. private bool _CheckChange = false;
14.
15. public MainForm()
16. {
17. InitializeComponent();
18. }
19.
20. private void MainForm_Load(object sender, EventArgs e)
21. {
22. // TODO: 這行程式碼會將資料載入 'database1DataSet.Table1' 資料表。您可以視需要進行移動或移除。
23. this.table1TableAdapter.Fill(this.database1DataSet.Table1);
24.
25. //設定DateTimePicker的高度
26. this.dateTimePicker1.Height = this.dataGridView1.Height;
27. }
28.
29. //將DateTimePicker控制項定位在DataGridView的Column上
30. private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
31. {
32. if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "date")
33. {
34. Rectangle r = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
35. r = this.dataGridView1.RectangleToScreen(r);
36. this.dateTimePicker1.Location = this.RectangleToClient(r).Location;
37. this.dateTimePicker1.Size = r.Size;
38. this._CheckChange = true;
39. this.dateTimePicker1.Text = this.dataGridView1.CurrentCell.Value.ToString();
40. this._CheckChange = false;
41. this.dateTimePicker1.Visible = true;
42. }
43. else
44. {
45. this.dateTimePicker1.Visible = false;
46. }
47. }
48.
49. //改變Column的值
50. private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
51. {
52. if (_CheckChange) return;
53. this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Text;
54. }
55. }
56. }
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Text;
7. using System.Windows.Forms;
8.
9. namespace DataGridViewDateTimePicker
10. {
11. public partial class MainForm : Form
12. {
13. private bool _CheckChange = false;
14.
15. public MainForm()
16. {
17. InitializeComponent();
18. }
19.
20. private void MainForm_Load(object sender, EventArgs e)
21. {
22. // TODO: 這行程式碼會將資料載入 'database1DataSet.Table1' 資料表。您可以視需要進行移動或移除。
23. this.table1TableAdapter.Fill(this.database1DataSet.Table1);
24.
25. //設定DateTimePicker的高度
26. this.dateTimePicker1.Height = this.dataGridView1.Height;
27. }
28.
29. //將DateTimePicker控制項定位在DataGridView的Column上
30. private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
31. {
32. if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "date")
33. {
34. Rectangle r = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
35. r = this.dataGridView1.RectangleToScreen(r);
36. this.dateTimePicker1.Location = this.RectangleToClient(r).Location;
37. this.dateTimePicker1.Size = r.Size;
38. this._CheckChange = true;
39. this.dateTimePicker1.Text = this.dataGridView1.CurrentCell.Value.ToString();
40. this._CheckChange = false;
41. this.dateTimePicker1.Visible = true;
42. }
43. else
44. {
45. this.dateTimePicker1.Visible = false;
46. }
47. }
48.
49. //改變Column的值
50. private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
51. {
52. if (_CheckChange) return;
53. this.dataGridView1.CurrentCell.Value = this.dateTimePicker1.Text;
54. }
55. }
56. }
2009年7月13日 星期一
Enum 轉成string & int
using System;
public class CSharpLab
{public enum State
{Init, Open, Proc, Close, Done = 9
}
public static void Test()
{State st = State.Init;
//列出所有名稱
foreach (string en in Enum.GetNames(typeof(State)))
Console.WriteLine("Enum Name: " + en);//列舉背後有值, 預設由零開始排, 但也可自訂
//TIPS: typeof(State)與st.GetType()都可取得列舉型別
foreach (int v in Enum.GetValues(st.GetType()))
Console.WriteLine("Enum Value: " + v.ToString());//將列舉轉為字串
Console.WriteLine("Enum To String: " + st.ToString());//將字串轉為列舉
st = (State)Enum.Parse(typeof(State), "proc", true);
Console.WriteLine("String To Enum: " + st);try {Console.WriteLine("String To Enum(not found): " + Enum.Parse(typeof(State), "WTF"));
} catch (Exception ex) {Console.WriteLine("Error when Enum.Parse: " + ex.Message);}
//將列舉轉為數字
Console.WriteLine("Enum to Int: " + st + " " + (int)st);//將數字轉回列舉
st = (State)9;
Console.WriteLine("Int to Enum: " + st);//小心數字轉換對不上時不會有錯誤,但會出現非列舉值
st = (State)100;
Console.WriteLine("Int(100) to Enum: " + st);//如果數字有連續,可以用+1, -1找上一個下一個
//注意: 以下範例並未檢查邊界及數值不連續的狀況,
//並非嚴謹寫法,僅為簡單示意,勿用於正式用途
st = State.Proc;
State next = (State)((int)st)+1;
State prev = (State)((int)st)-1;
Console.WriteLine("Now = " + st + " Next = " + next + " Prev = " + prev);}
}
Winform DateTimePicker顯示民國年
Dim ci As CultureInfo = New CultureInfo("zh-TW", True)
ci.DateTimeFormat.Calendar = New TaiwanCalendar
MessageBox.Show(DateTimePicker1.Value.ToString("yy/MM/dd", ci))
MessageBox.Show(DateTimePicker1.Value.ToString("ggyyyy/MM/dd", ci)) '顯示中華民國
ci.DateTimeFormat.Calendar = New TaiwanCalendar
MessageBox.Show(DateTimePicker1.Value.ToString("yy/MM/dd", ci))
MessageBox.Show(DateTimePicker1.Value.ToString("ggyyyy/MM/dd", ci)) '顯示中華民國
2009年7月12日 星期日
2009年7月6日 星期一
MS SQl Split Function
CREATE FUNCTION dbo.fnSYS_Split(@String varchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items varchar(4000) COLLATE Chinese_Taiwan_Stroke_CI_AI)
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE varchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
-- ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
-- following line added 10/06/04 as null
-- values cause issues
IF @String IS NULL RETURN
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
RETURNS @Results TABLE (Items varchar(4000) COLLATE Chinese_Taiwan_Stroke_CI_AI)
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE varchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
-- ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
-- following line added 10/06/04 as null
-- values cause issues
IF @String IS NULL RETURN
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
2009年7月2日 星期四
MySQL 系統指令
MySQL.exe
登入
mysql -h hostname -u username -p
設定密碼
set password for root@localhost=password('password');
產生一般用帳號
grant create, create temporary tables, delete, execute,index, insert, lock tables, select,show databases, update
on *.*
to %username% identified by '%password%'
顯示資料庫
show databases
切換資料庫
use databasename
顯示資料表
show tables
登入
mysql -h hostname -u username -p
設定密碼
set password for root@localhost=password('password');
產生一般用帳號
grant create, create temporary tables, delete, execute,index, insert, lock tables, select,show databases, update
on *.*
to %username% identified by '%password%'
顯示資料庫
show databases
切換資料庫
use databasename
顯示資料表
show tables
Winform Combox 新增 Item
'由單純的ComboBox的Items 增加
With ComboBox1
For i As Integer = 0 To 10
Items.Add(New simpleArrayList("Test" & i.ToString, i.ToString))
Next
End With
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Value"
ComboBox1.Items.Add(New simpleArrayList("Finally", "Finally"))
'由DataSource改變時的作法
Dim array As New ArrayList
For i As Integer = 0 To 10
array.Add(New simpleArrayList("Test" & i.ToString, i.ToString))
Next
Me.ComboBox1.DataSource = array
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Value"
array.Add(New simpleArrayList("Finally", "Finally"))
Dim bm As BindingManagerBase = Me.ComboBox1.BindingContext(array)
Dim cm As CurrencyManager = CType(bm, CurrencyManager)
If Not cm Is Nothing Then
cm.Refresh()
End If
With ComboBox1
For i As Integer = 0 To 10
Items.Add(New simpleArrayList("Test" & i.ToString, i.ToString))
Next
End With
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Value"
ComboBox1.Items.Add(New simpleArrayList("Finally", "Finally"))
'由DataSource改變時的作法
Dim array As New ArrayList
For i As Integer = 0 To 10
array.Add(New simpleArrayList("Test" & i.ToString, i.ToString))
Next
Me.ComboBox1.DataSource = array
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Value"
array.Add(New simpleArrayList("Finally", "Finally"))
Dim bm As BindingManagerBase = Me.ComboBox1.BindingContext(array)
Dim cm As CurrencyManager = CType(bm, CurrencyManager)
If Not cm Is Nothing Then
cm.Refresh()
End If
HashTable 不區分大小寫
Imports System
Imports System.Collections
Imports System.Globalization
Public Class SamplesHashtable
Public Shared Sub Main()
' Create a Hashtable using the default hash code provider and the default comparer.
Dim myHT1 As New Hashtable
myHT1.Add("FIRST", "Hello")
myHT1.Add("SECOND", "World")
myHT1.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the culture of the current thread.
Dim myHT2 As New Hashtable(New CaseInsensitiveHashCodeProvider, New CaseInsensitiveComparer)
myHT2.Add("FIRST", "Hello")
myHT2.Add("SECOND", "World")
myHT2.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the InvariantCulture.
Dim myHT3 As New Hashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant)
myHT3.Add("FIRST", "Hello")
myHT3.Add("SECOND", "World")
myHT3.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
Dim myCul As New CultureInfo("tr-TR")
Dim myHT4 As New Hashtable(New CaseInsensitiveHashCodeProvider(myCul), New CaseInsensitiveComparer(myCul))
myHT4.Add("FIRST", "Hello")
myHT4.Add("SECOND", "World")
myHT4.Add("THIRD", "!")
' Search for a key in each hashtable.
Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("fiRst"))
Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))
Console.WriteLine("first is in myHT4: {0}", myHT4.ContainsKey("first"))
Console.ReadLine()
End Sub 'Main
End Class 'SamplesHashtable
Imports System.Collections
Imports System.Globalization
Public Class SamplesHashtable
Public Shared Sub Main()
' Create a Hashtable using the default hash code provider and the default comparer.
Dim myHT1 As New Hashtable
myHT1.Add("FIRST", "Hello")
myHT1.Add("SECOND", "World")
myHT1.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the culture of the current thread.
Dim myHT2 As New Hashtable(New CaseInsensitiveHashCodeProvider, New CaseInsensitiveComparer)
myHT2.Add("FIRST", "Hello")
myHT2.Add("SECOND", "World")
myHT2.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the InvariantCulture.
Dim myHT3 As New Hashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, CaseInsensitiveComparer.DefaultInvariant)
myHT3.Add("FIRST", "Hello")
myHT3.Add("SECOND", "World")
myHT3.Add("THIRD", "!")
' Create a Hashtable using a case-insensitive code provider and a case-insensitive comparer,
' based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
Dim myCul As New CultureInfo("tr-TR")
Dim myHT4 As New Hashtable(New CaseInsensitiveHashCodeProvider(myCul), New CaseInsensitiveComparer(myCul))
myHT4.Add("FIRST", "Hello")
myHT4.Add("SECOND", "World")
myHT4.Add("THIRD", "!")
' Search for a key in each hashtable.
Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("fiRst"))
Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))
Console.WriteLine("first is in myHT4: {0}", myHT4.ContainsKey("first"))
Console.ReadLine()
End Sub 'Main
End Class 'SamplesHashtable
Windows 系統環境變數
環境變數是儲存與系統相關的資訊,它的格式很簡單,就是將字串值指定給變數名稱。系統在開機之後,會自行設定若干環境變數,以作為系統運作之用,而這些環境變數的值,原本是存放在登錄資料庫,開機之後才自登錄資料庫取出,並指定給環境變數。
舉例來說,雖然安裝程式預設會將Windows系統安裝到C磁碟機的Windows資料夾、會將軟體安裝到C磁碟機的Program Files資料夾,但這只是預設值,不見得每個Windows都如此,而這些資料夾的實際位置,也會記錄在特定的環境變數:
%WinDir%:記錄Windows系統資料夾
%ProgramFiles%:記錄軟體安裝資料夾
也就是說,透過環境變數,將能夠得知系統的相關資訊。環境變數大多數是為程式所用,例如批次檔就常使用環境變數。不過,我們也可以『檔案總管』或『執行』交談窗,配合記錄資料夾位置的環境變數,快速開啟資料夾。例如將%windir%輸入到『檔案總管』的『網址』列,再按下Enter按鍵,『檔案總管』隨即切換到Windows系統資料夾。
系統存取環境變數的順序
1. Autoexec.bat
2. 系統變數
3. 使用者變數
也就是說,相同變數名稱同時經由上述三種方式設定之後,在『使用者變數』所設定的變數值,會蓋過在『系統變數』或『Autoexec.bat'所設定的值;而在『系統變數』所設定的值,會蓋過在『Autoexec.bat'所設定的值。
Windows系統內建的常見環境變數
%SystemDrive%:系統磁碟機,預設是C:
%SystemRoot%:系統根目錄,預設是C:\WINNT或C:\WINDOWS
%SystemDirectory%:系統目錄,預設是C:\WINNT\System32或C:\WINDOWS\System32
%WinDir%:Windows目錄,預設是C:\WINNT或C:\WINDOWS
%ProgramFiles%:應用程式目錄,預設是C:\Program Files
%Temp%、%Tmp%:暫存檔目錄 %HomeDrive%:使用者目錄的磁碟機
%HomePath%:使用者家目錄
(以上環境變數可以『檔案總管』試之,或在DOS視窗以echo指令顯示其值;以下的環境變數隻能以DOS視窗以echo指令顯示其值)
%OS%:作業系統名稱,其值固定為Windows_NT
%UserDomain%:包含使用者帳號的網域名稱,或者電腦名稱
%UserName%:使用者帳號名稱
簡單的應用
想快速切換到暫存檔目錄,然後刪除裡面的垃圾檔案嗎?(最好是在開機之初)以上述方式將%Temp%或%Tmp%輸入到『檔案總管』的『網址』列,即可切換到暫存檔目錄,接著就能刪除裡面的檔案了。
Windows環境變數列表
每部電腦的環境變數大致相同,但也可能會有若干差異,這是因為安裝的軟體或使用者可能自行設定了環境變數;在『命令提示字元』視窗利用set指令,就能列出完整的環境變數。
除了上篇文章提及了若干,以下再補述其他環境變數;這些環境變數可以『檔案總管』試之,或在DOS視窗以echo指令顯示其值:
%ALLUSERSPROFILE%:All Users設定檔的資料夾位置。
%APPDATA%:目前使用者的Application Data資料夾位置。
%CD%:目前的工作資料夾。
%CLIENTNAME%:目前使用者的NETBIOS電腦名稱。
%CMDCMDLINE%:處理目前命令提示字元視窗命令的cmd.exe的完整路徑。
%CMDEXTVERSION%:目前Command Processor Extensions的版本。
%CommonProgramFiles%:Common Files資料夾的路徑。
%COMPUTERNAME%:電腦名稱。
%COMSPEC%::命令提示字元視窗的解譯程式路徑,通常與%CMDCMDLINE%相同。
%DATE%:目前的系統日期。
%ERRORLEVEL%:最近執行過的命令的錯誤碼;非零的值表示發生過的錯誤碼。
%HomeDrive%:使用者目錄的磁碟機。
%HomePath%:使用者家目錄。
%HOMESHARE%:目前使用者共用資料夾的網路路徑。
%LOGONSEVER%:目前使用者所登入的網路控制器名稱。
%NUMBER_OF_PROCESSORS%:電腦的處理器數量。
%OS%:作業系統名稱,其值固定為Windows_NT。
%Path%:執行檔的搜尋路徑。
%PATHEXT%:作業系統是為執行檔的副檔名。
%PROCESSOR_ARCHITECTURE%:處理器的架構名稱,例如x86。
%PROCESSOR_IDENTFIER%:說明處理器的文字(不一定會有此環境變數)。
%PROCESSOR_LEVEL%:處理器的model number。
%PROCESSOR_REVISION%:處理器的revision number。
%ProgramFiles%:應用程式目錄,預設是C:\Program Files。
%PROMPT%:目前解譯程式的命令提示字串。
%RANDOM%:顯示0到32767之間的十進位整數亂數。
%SESSIONNAME%:連上終端伺服器的session names。
%SystemDrive%:系統磁碟機,預設是C:。
%SystemRoot%:系統根目錄,預設是C:\WINNT或C:\WINDOWS。
%SystemDirectory%:系統目錄,預設是C:\WINNT\System32或C:\WINDOWS\System32。
%Temp%、%Tmp%:暫存檔目錄。
%TIME%:目前的系統時間。
%UserDomain%:包含使用者帳號的網域名稱,或者電腦名稱。
%UserName%:使用者帳號名稱。
%USERPROFILE%:目前使用者的設定檔路徑。
%WinDir%:Windows目錄,預設是C:\WINNT或C:\WINDOWS。
舉例來說,雖然安裝程式預設會將Windows系統安裝到C磁碟機的Windows資料夾、會將軟體安裝到C磁碟機的Program Files資料夾,但這只是預設值,不見得每個Windows都如此,而這些資料夾的實際位置,也會記錄在特定的環境變數:
%WinDir%:記錄Windows系統資料夾
%ProgramFiles%:記錄軟體安裝資料夾
也就是說,透過環境變數,將能夠得知系統的相關資訊。環境變數大多數是為程式所用,例如批次檔就常使用環境變數。不過,我們也可以『檔案總管』或『執行』交談窗,配合記錄資料夾位置的環境變數,快速開啟資料夾。例如將%windir%輸入到『檔案總管』的『網址』列,再按下Enter按鍵,『檔案總管』隨即切換到Windows系統資料夾。
系統存取環境變數的順序
1. Autoexec.bat
2. 系統變數
3. 使用者變數
也就是說,相同變數名稱同時經由上述三種方式設定之後,在『使用者變數』所設定的變數值,會蓋過在『系統變數』或『Autoexec.bat'所設定的值;而在『系統變數』所設定的值,會蓋過在『Autoexec.bat'所設定的值。
Windows系統內建的常見環境變數
%SystemDrive%:系統磁碟機,預設是C:
%SystemRoot%:系統根目錄,預設是C:\WINNT或C:\WINDOWS
%SystemDirectory%:系統目錄,預設是C:\WINNT\System32或C:\WINDOWS\System32
%WinDir%:Windows目錄,預設是C:\WINNT或C:\WINDOWS
%ProgramFiles%:應用程式目錄,預設是C:\Program Files
%Temp%、%Tmp%:暫存檔目錄 %HomeDrive%:使用者目錄的磁碟機
%HomePath%:使用者家目錄
(以上環境變數可以『檔案總管』試之,或在DOS視窗以echo指令顯示其值;以下的環境變數隻能以DOS視窗以echo指令顯示其值)
%OS%:作業系統名稱,其值固定為Windows_NT
%UserDomain%:包含使用者帳號的網域名稱,或者電腦名稱
%UserName%:使用者帳號名稱
簡單的應用
想快速切換到暫存檔目錄,然後刪除裡面的垃圾檔案嗎?(最好是在開機之初)以上述方式將%Temp%或%Tmp%輸入到『檔案總管』的『網址』列,即可切換到暫存檔目錄,接著就能刪除裡面的檔案了。
Windows環境變數列表
每部電腦的環境變數大致相同,但也可能會有若干差異,這是因為安裝的軟體或使用者可能自行設定了環境變數;在『命令提示字元』視窗利用set指令,就能列出完整的環境變數。
除了上篇文章提及了若干,以下再補述其他環境變數;這些環境變數可以『檔案總管』試之,或在DOS視窗以echo指令顯示其值:
%ALLUSERSPROFILE%:All Users設定檔的資料夾位置。
%APPDATA%:目前使用者的Application Data資料夾位置。
%CD%:目前的工作資料夾。
%CLIENTNAME%:目前使用者的NETBIOS電腦名稱。
%CMDCMDLINE%:處理目前命令提示字元視窗命令的cmd.exe的完整路徑。
%CMDEXTVERSION%:目前Command Processor Extensions的版本。
%CommonProgramFiles%:Common Files資料夾的路徑。
%COMPUTERNAME%:電腦名稱。
%COMSPEC%::命令提示字元視窗的解譯程式路徑,通常與%CMDCMDLINE%相同。
%DATE%:目前的系統日期。
%ERRORLEVEL%:最近執行過的命令的錯誤碼;非零的值表示發生過的錯誤碼。
%HomeDrive%:使用者目錄的磁碟機。
%HomePath%:使用者家目錄。
%HOMESHARE%:目前使用者共用資料夾的網路路徑。
%LOGONSEVER%:目前使用者所登入的網路控制器名稱。
%NUMBER_OF_PROCESSORS%:電腦的處理器數量。
%OS%:作業系統名稱,其值固定為Windows_NT。
%Path%:執行檔的搜尋路徑。
%PATHEXT%:作業系統是為執行檔的副檔名。
%PROCESSOR_ARCHITECTURE%:處理器的架構名稱,例如x86。
%PROCESSOR_IDENTFIER%:說明處理器的文字(不一定會有此環境變數)。
%PROCESSOR_LEVEL%:處理器的model number。
%PROCESSOR_REVISION%:處理器的revision number。
%ProgramFiles%:應用程式目錄,預設是C:\Program Files。
%PROMPT%:目前解譯程式的命令提示字串。
%RANDOM%:顯示0到32767之間的十進位整數亂數。
%SESSIONNAME%:連上終端伺服器的session names。
%SystemDrive%:系統磁碟機,預設是C:。
%SystemRoot%:系統根目錄,預設是C:\WINNT或C:\WINDOWS。
%SystemDirectory%:系統目錄,預設是C:\WINNT\System32或C:\WINDOWS\System32。
%Temp%、%Tmp%:暫存檔目錄。
%TIME%:目前的系統時間。
%UserDomain%:包含使用者帳號的網域名稱,或者電腦名稱。
%UserName%:使用者帳號名稱。
%USERPROFILE%:目前使用者的設定檔路徑。
%WinDir%:Windows目錄,預設是C:\WINNT或C:\WINDOWS。
Reporting Service WebService呼叫語法
Dim rs As New ReportService.ReportingService
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim paras(4) As ReportService.ParameterValue
paras(0) = New ReportService.ParameterValue
paras(0).Name = "CenterID"
paras(0).Value = Me.ddlCenterID.SelectedValue
paras(1) = New ReportService.ParameterValue
paras(1).Name = "ReceiveNO"
paras(1).Value = Me.txtReceiveNO.Text.Trim
paras(2) = New ReportService.ParameterValue
paras(2).Name = "BatchNO"
paras(2).Value = Me.txtBatchNO.Text.Trim
paras(3) = New ReportService.ParameterValue
paras(3).Name = "StartDate"
paras(3).Value = Me.HRS_UclDates1.GetDate1
paras(4) = New ReportService.ParameterValue
paras(4).Name = "EndDate"
paras(4).Value = Me.HRS_UclDates1.GetDate2
Dim result() As Byte
Dim deviceinfo As New StringBuilder
Dim path As String = "/DIS_Reort1/QIS_PForeignInspectionDocument"
deviceinfo.Append("")
deviceinfo.Append("" & 1.2 + Val(Me.txtMarginTop.Text) & "cm ")
deviceinfo.Append("" & 2.6 + Val(Me.txtMarginTop.Text) * -1 & "cm ")
deviceinfo.Append("" & 1.1 + Val(Me.txtMarginLeft.Text) & "cm ")
deviceinfo.Append("" & 0.3 + Val(Me.txtMarginLeft.Text) * -1 & "cm ")
deviceinfo.Append("20.3cm ")
deviceinfo.Append("30.7cm ")
deviceinfo.Append(" ")
result = rs.Render(path, "PDF", Nothing, deviceinfo.ToString, paras, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
Me.Response.Clear()
Me.Response.ContentType = "application/pdf"
Dim filename As String = path.Substring(path.LastIndexOf("/") + 1) & ".pdf"
Me.Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
Me.Response.BinaryWrite(result)
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim paras(4) As ReportService.ParameterValue
paras(0) = New ReportService.ParameterValue
paras(0).Name = "CenterID"
paras(0).Value = Me.ddlCenterID.SelectedValue
paras(1) = New ReportService.ParameterValue
paras(1).Name = "ReceiveNO"
paras(1).Value = Me.txtReceiveNO.Text.Trim
paras(2) = New ReportService.ParameterValue
paras(2).Name = "BatchNO"
paras(2).Value = Me.txtBatchNO.Text.Trim
paras(3) = New ReportService.ParameterValue
paras(3).Name = "StartDate"
paras(3).Value = Me.HRS_UclDates1.GetDate1
paras(4) = New ReportService.ParameterValue
paras(4).Name = "EndDate"
paras(4).Value = Me.HRS_UclDates1.GetDate2
Dim result() As Byte
Dim deviceinfo As New StringBuilder
Dim path As String = "/DIS_Reort1/QIS_PForeignInspectionDocument"
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
deviceinfo.Append("
result = rs.Render(path, "PDF", Nothing, deviceinfo.ToString, paras, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
Me.Response.Clear()
Me.Response.ContentType = "application/pdf"
Dim filename As String = path.Substring(path.LastIndexOf("/") + 1) & ".pdf"
Me.Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
Me.Response.BinaryWrite(result)
Reporting Service 內建函數
countdistinct(field.value)計算不重覆筆數
rownumber(nothing)計算筆數(逐筆累計),nothing:範圍為所有資料表
runingvalue(運算式,Function,Scope)累計(逐筆累計),Scope:nothing-->範圍為所有資料表
example:runingvalue(field.a *field.b,sum,nothing)
avg所有目空值的平均值
count計算資料筆數
countrows指定值在特定範圍內的資料筆數
first第一筆資料的值
last最後一筆資料的值
max非空值的最大值
min非空值的最小值
sum總合
rownumber(nothing)計算筆數(逐筆累計),nothing:範圍為所有資料表
runingvalue(運算式,Function,Scope)累計(逐筆累計),Scope:nothing-->範圍為所有資料表
example:runingvalue(field.a *field.b,sum,nothing)
avg所有目空值的平均值
count計算資料筆數
countrows指定值在特定範圍內的資料筆數
first第一筆資料的值
last最後一筆資料的值
max非空值的最大值
min非空值的最小值
sum總合
MS SQL Cursor 語法
DECLARE MY_CURSOR Cursor FOR
([Select 語法])
open MY_CURSOR
FETCH NEXT FROM MY_CURSOR Into [接收變數]
--判斷狀態
WHILE(@@FETCH_STATUS=0)
--中間程式段
begin
[處理程式]
--移至下一筆
FETCH NEXT FROM MY_CURSOR INTO [接收變數]
end
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
([Select 語法])
open MY_CURSOR
FETCH NEXT FROM MY_CURSOR Into [接收變數]
--判斷狀態
WHILE(@@FETCH_STATUS=0)
--中間程式段
begin
[處理程式]
--移至下一筆
FETCH NEXT FROM MY_CURSOR INTO [接收變數]
end
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
VB讀取EXCEL
文章來源 ptt
開excel
工具功能表-巨集-錄製新巨集-確定
(開始記錄你的操作)
檔案-開新檔案
輸入幾筆數值(溫度值)
插入功能表-圖表-選擇你要的圖表樣式-數值範圍-特殊設定
工具功能表-巨集-停止錄製
工具功能表-巨集-Visual Basic編輯器
模組-Module1
把程式碼複製到 VB6 裡
在 VB6 裡,專案功能表-設定引用項目-選擇 Microsoft Excel 10.0 Object Library
確定
範例(VB6的寫法跟 Excel 錄製下來的內容會有些差異):
Public Sub ExportToExcel()
'建立Excel
Dim excl As New Excel.Application
Dim wb As Excel.Workbook, ws As Excel.Worksheet, ap As Excel.Application
Set wb = excl.Workbooks.Add
If wb.Worksheets.Count = 0 Then
Set ws = wb.Worksheets.Add
Else
Set ws = wb.Worksheets(1)
End If
Set ap = ws.Application
'將資料(溫度值)置入儲存格中(自己視需求修改此段程式碼@_@)
ap.ActiveCell.FormulaR1C1 = "33"
ap.Range("B1").Select
ap.ActiveCell.FormulaR1C1 = "44"
ap.Range("B2").Select
'加入圖表(自己視需求修改此段程式碼@_@)
Dim ct As Chart
ws.Application.Charts.Add
Set ct = ws.Application.ActiveChart
ct.ChartType = xlLine
ct.SetSourceData ws.Application.Sheets("Sheet1").Range("A1:D1"), xlRows
ct.Location xlLocationAsObject, "Sheet1"
With ws.Application.ActiveChart
.HasTitle = False
.Axes(xlCategory, xlPrimary).HasTitle = False
.Axes(xlValue, xlPrimary).HasTitle = False
End With
ws.Application.Range("A1").Select
'儲存檔案(檔案已存在會覆蓋檔案),並結束Excel
ap.DisplayAlerts = False
ws.SaveAs "c:\temp\xd.xls"
wb.Close
excl.Quit
End Sub
開excel
工具功能表-巨集-錄製新巨集-確定
(開始記錄你的操作)
檔案-開新檔案
輸入幾筆數值(溫度值)
插入功能表-圖表-選擇你要的圖表樣式-數值範圍-特殊設定
工具功能表-巨集-停止錄製
工具功能表-巨集-Visual Basic編輯器
模組-Module1
把程式碼複製到 VB6 裡
在 VB6 裡,專案功能表-設定引用項目-選擇 Microsoft Excel 10.0 Object Library
確定
範例(VB6的寫法跟 Excel 錄製下來的內容會有些差異):
Public Sub ExportToExcel()
'建立Excel
Dim excl As New Excel.Application
Dim wb As Excel.Workbook, ws As Excel.Worksheet, ap As Excel.Application
Set wb = excl.Workbooks.Add
If wb.Worksheets.Count = 0 Then
Set ws = wb.Worksheets.Add
Else
Set ws = wb.Worksheets(1)
End If
Set ap = ws.Application
'將資料(溫度值)置入儲存格中(自己視需求修改此段程式碼@_@)
ap.ActiveCell.FormulaR1C1 = "33"
ap.Range("B1").Select
ap.ActiveCell.FormulaR1C1 = "44"
ap.Range("B2").Select
'加入圖表(自己視需求修改此段程式碼@_@)
Dim ct As Chart
ws.Application.Charts.Add
Set ct = ws.Application.ActiveChart
ct.ChartType = xlLine
ct.SetSourceData ws.Application.Sheets("Sheet1").Range("A1:D1"), xlRows
ct.Location xlLocationAsObject, "Sheet1"
With ws.Application.ActiveChart
.HasTitle = False
.Axes(xlCategory, xlPrimary).HasTitle = False
.Axes(xlValue, xlPrimary).HasTitle = False
End With
ws.Application.Range("A1").Select
'儲存檔案(檔案已存在會覆蓋檔案),並結束Excel
ap.DisplayAlerts = False
ws.SaveAs "c:\temp\xd.xls"
wb.Close
excl.Quit
End Sub
訂閱:
意見 (Atom)