回「微軟線上專家對談」首頁

問題數

問題描述與解答

Q1: 請問在 Win Form DataGrid 的 PreferredColumnWidth 屬性設定除了指定 pixels (如:75)之外 ,有無方法可以設定成最適欄寬(如同 EXCEL最適欄寬)? 即畫面一出來時,已經是最適欄寬了
A: Excel 也是做了一些計算才算出最合適的寬度的。恐怕,你要自己寫代碼來算了。
Q2: 有2個textbox,比如說:textbox a and textbox b,當textbox a內 容改變的時候 ,textbox b也會自動跟著變,我的問題是:當按了 ctrl+z後,textbox a 有undo,但是textbox b卻沒有undo,請問該如何解決
A: 你可以在第二個TextBox 中,偵測 Change 時間。當第一個變化的時候,第二個也會自動的變化。
Q3: 如果要偵測使用者電腦的螢幕解析度來動態調整作業畫面的話,該如何作呢?
A:

可以用以下方法來獲得:

file://建 立一個矩形物件 Rectangle rect = new Rectangle ( ) ; file://通過一個函數對這個矩形物件賦值,這些值就是螢幕的工作 區域 rect = Screen.GetWorkingArea ( this ) ; MessageBox.Show ( "本機器的解析度是" + rect.Width.ToString ( ) + "*" + rect.Height.ToString ( ) ) ;

Q4: 我寫了一個.NET windows form的應用程式,要讓使用者進行安裝,那我可以只把CLR放進來就好了嗎 ?還是應該怎麼做才能讓沒裝.NET framework的client也能安裝這個application
A: VS.NET 有一個安裝的專案。你只要建立這麼一個專案,然後告訴他那個程式需要安裝。支援windows 和 ASP.NET專案。
Q5: 在哪裡能找到 System.Drawing.Printing.PrintDocument
A:

System.Drawing.Printing 命名空間 (Namespace) 提供列印相關的服務。 通常,您會建立 PrintDocument 類別的新執行個體 (Instance)、設定描述要列印的內容之屬性,並且呼叫 Print 方法來實際列印文件。使用 PrintPageEventArgs.Graphics 屬性來指定要列印的輸出。如果您正列印文字 檔,請以下列方式使用 StreamReader :從資料流一次讀取一行,並呼叫 DrawString 方法在圖形物件中繪製此行。如需這個程序的詳細資訊,請參閱 Graphics 和 StreamReader 類別。 在衍生類別 (Derived Class) 中實作時, PrintController 會控制如何列印 PrintDocument 。 PrintDocument.Print 方法會叫用 (Invoke) 列印控制程式的 OnStartPrint 、 OnEndPrint 、 OnStartPage 和 OnEndPage 方法,這些方法會依序 告知印表機如何列印文件。如需列印對話方塊的詳細資訊,請參閱 PrintDialog 和 PageSetupDialog 。 預覽列印程序會使用特殊的列印控制程式、對話方塊和控制項。如需這類列印控制程式 和對話方塊的範例,請參閱 PreviewPrintController 、 PrintPreviewDialog 和 PrintPreviewControl 。

Q6: 我們在 VS.NET 連接到SQL stored procedure 時,VS.NET 會建立 出該DataSet的 XSD。(Design Time) 我的問題是,若這個stored procedure 在執行的階段,才知道 return dataset 的長相,這時候,VS.NET並無法產生 XSD。 那 VS.NET 的 developpers 要如何解決這個問題?
A: 我的建議是:這種情況下,不要使用typed dataset at design time。就用普通的辦 法來處理DataSet。
Q7: 請各位推薦一下,如果client要跑.NET application (winforms),是否一定要win2k,如果是win98 or NT可以嗎
A: WinForm應用程式可在98,NT4以及Win2K或XP以上版本的OS執行。
Q8: 我設了一個Textbox 以及Combobox,之後在form裡設了 KeyPreview,很奇怪的是,KeyPreview在Textbox能work,但是在 Combobox卻不work,請問是不是哪裡設定出了問題
A: You must have the .NET Framework Service Pack 2 (SP2) installed to apply this hotfix.
Q9: 在 Web Form 中是否有 Windows Form 中的 TabControl 元件 可以使用,若無是否有其他的類似元件可以替代?
A:

您可在在設計工具 (Designer) 中或使用程式碼 (Code),從 Windows Form TabControl 來加入和移除索引標籤。您可以在 Run Time 及設計階段加入或移除索引 標籤。 a.. 使用 TabPages 屬性的 Add 方法。 ' Visual Basic Dim myTabPage As New TabPage() myTabPage.Text = "TabPage" & (TabControl1.TabPages.Count + 2) TabControl1.TabPages.Add(myTabPage)

// C# string title = "TabPage " + (tabControl1.TabCount + 2).ToString(); TabPage myTabPage = new TabPage(title); tabControl1.TabPages.Add(myTabPage)

Q10: 在.NET Framework中目前有提供可以與GPS(Gobal Position System)進行資訊交換的類別嗎?
A: 目前沒有內建此功能,需自行透過Win32 API與RS232聯繫。
Q11: 在TreeView能否使用backgroundimage? 如行,該怎麼做
A:

Try overriding the WndProc and then colling a private method like so:

************************************************ Public Const WM_PAINT As Integer = &HF

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

Select Case m.Msg

Case WM_PAINT WMPaint(m)

Case Else MyBase.WndProc(m)

End Select

End Sub

Private Sub WMPaint(ByRef m As Message) Dim g As Graphic = Me.CreateGraphics()

'Make sure the TreeView gets the Paint message... MyBase.WndProc(m)

'Do your painting here with the "g" Graphic object...

g.Dispose '<-- Make sure to call this since you allocated it!

'Let Windows know you handled the WM_PAINT Message... m.Result = IntPtr.Zero

End Sub

Q12: 不知在winform中有沒有ListItem
A:

下列範例是一個完整的應用程式,說明可以如何使用 ListBox 類別實作的 ListControl 類別的 DataSource 、 DisplayMember 、 ValueMember 和 SelectedValue 成員。範例會載入一個 ArrayList 和清單方塊。使用者從清單方塊中 選取項目時,會使用選取的值傳回與所選取項目關聯的資料。 [Visual Basic] Imports System.Windows.Forms Imports System.Drawing Imports System.Collections

Public Class USState

Private myShortName As String Private myLongName As String

Public Sub New(ByVal strlongName As String, ByVal strShortName As String) MyBase.New() Me.myShortName = strShortName Me.myLongName = strLongName End Sub

Public ReadOnly Property ShortName() As String Get Return myShortName End Get End Property

Public ReadOnly Property LongName() As String Get Return myLongName End Get End Property

Public Overrides Function ToString() As String Return Me.ShortName & " - " & Me.LongName End Function End Class

Public Class ListBoxSample3 Inherits Form Friend WithEvents ListBox1 As ListBox = New ListBox() Dim textBox1 As TextBox = New TextBox()

<System.STAThreadAttribute()> _ Public Shared Sub Main() System.Windows.Forms.Application.Run(New ListBoxSample3()) End Sub

Public Sub New() Me.AutoScaleBaseSize = New Size(5, 13) Me.ClientSize = New Size(292, 181) Me.Text = "ListBox Sample1"

ListBox1.Location = New Point(24, 16) ListBox1.Name = "ListBox1" ListBox1.Size = New Size(232, 130)

textBox1.Location = New Point(24, 160) textBox1.Name = "textBox1" textBox1.Size = New Size(40, 24) Me.Controls.AddRange(New Control() {ListBox1, textBox1})

' Populates the list box using DataSource. ' DisplayMember is used to display just the long name of each state. Dim USStates As New ArrayList() USStates.Add(New USState("Washington", "WA")) USStates.Add(New USState("West Virginia", "WV")) USStates.Add(New USState("Wisconsin", "WI")) USStates.Add(New USState("Wyoming", "WY"))

ListBox1.DataSource = USStates ListBox1.DisplayMember = "LongName" ListBox1.ValueMember = "ShortName"

End Sub

Private Sub InitializeComponent()

End Sub

Private Sub ListBox1_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedValueChanged If ListBox1.SelectedIndex <> -1 Then textBox1.Text = ListBox1.SelectedValue End If End Sub End Class

Q13: 我在更改datagrid資料時,無法更新
A: Try accptchange,databind
Q14: mouse是不是一定要mouse點二下才行
A: 是的。要點兩下以確保選中。
Q15: 如果不使用Crystal Report 而直接在 Win Form 上顯示統計圖表 (如:長條圖),有什麼Component可用?
A: you can use MSChart control
Q16: win98可以跑.NET framework嗎?效能會不會較差?
A: It is ok. You can setup .net framework on windows 98
Q17: 我該如何用folderbroswer dialogbox? 就像openfile dialogbox那樣?
A:

http://www.gotdotnet.com/team/vb/

FolderBrowser.exe This sample contains a custom object called a FolderBrowser that wraps the functionality of the shell folder browser. This is an example of creating a .NET wrapper around some API functionality.

Q18: 我該如何在CheckedListBox指定一個特定值?
A: 能否請您提供進一步的資訊?我們在得到您的進一步資訊後,將儘快處理
Q19: 我想知道是否可以將某些項目放到db filed中成為CheckedItem
A: 我能 否請您提供進一步的資訊?我們在得到您的進一步資訊後,將儘快處理
Q20: 我把資料庫的資料抓出來存到xml裡,之後修改xml裡的資料,再存回去資料庫,可是資料庫如何知道那些資料要新增 ,那些要修改
A: 如果您是使用DataSet轉成XML的話,那您在編修時最好先將該XML轉回DataSet,再透過 DataSet的function來異動資料,如此系統則可自動維護資料的異動情形,不必您太費 心思。
Q21: 像title,scroll bar可以customerize嗎? 我是用.NET,如果可以,請問要如何customerize
A: 你想如何customize?我們在得到您的進一步資訊後,將儘快處理
Q22: 如何在安裝部署中將Crystal Resport加入
A: 317789 INFO: Licensing and Support for Crystal Reports for Visual Studio .NET http://support.microsoft.com/?id=317789
Q23: 我在form裡有用一些tag, 但還要再用的話, 可以直接複製就好了 嗎, 或者不行?
A: 基本上,只要複製就可以了。
Q24: 我想知道要怎樣得到local machine的IP 或是電腦名稱
A:

可以用以下代碼達到:

Dim h As System.Net.IPHostEntry = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName) Console.WriteLine(CType(h.AddressList.GetValue(0), IPAddress).ToString)

Q25: 之前使用set_ImageIndex(int)設定以image當成label,但現在想把它移掉 ,請問該如何移,因為我試了一些方法好像都無法移掉
A: set it to -1.
Q26: 如果在一個Data Grid中要進行不同資料列的拖曳動作 (ex:選取某一列,然後將這列移動到某一列的上方)該如何進行呢?
A: 這個問題比較複雜。DataGrid 沒有提供相應的方法 。可以考慮繼承DataGrid後,自己來寫一些方法。也可以從以下link中找到相關資料:
http://www.c-sharpcorner.com/Code/2002/June/DataGridCustomizationP1.asp
Q27: 有什麼方法可以設定DataGrid 的Cells依照不同的條件顯示不同的顏色和背景色(如:金額欄位小於10000顯示紅色,大於10000則顯示藍色)
A: It seems can not.
Q28: 因為常會忘記下 conn.close 指令,是否有方法設定ASP執行完自動 close 呢?
A: I suggest you call conn.close in the Session_OnEnd event.
Q29: 如何將System.Windows.Forms.Keys轉成 System.Windows.Forms.Shortcut
A: 他們完全不同的兩樣東西。
Q30: 在design view中可以增加toolbar嗎? 因為我在winform toolbox中找不到
A: 可以的。 在工具箱中選擇 toolsbar,再到屬性中的 "buttons" 集合中加入您的 button 的成員。
Q31: 在 Win Form 程式中,如何呼叫另一個 Win Form 畫面(非另一個程 式),例如在訂單輸入畫面中,使用者按一個按鈕(查詢客戶編號) 後,即顯示另一個畫面於主畫面之上
A: What control are you using?
Q32: 假設第2個畫面的Class為Form2,使用下列程式片斷即可: Dim myForm2 As New Form2() myForm2.Show()
A:

1.You can use ADO.NET to do this job. Have you tried the GotDotNet samples at http://www.gotdotnet.com/ . You can also search MSDN for ADO.NET.

313483 INFO: Roadmap for ADO.NET DataAdapter Objects http://support.microsoft.com/?id=313483 313480  INFO: Roadmap for .NET Data Providers http://support.microsoft.com/?id=313480

2.This is not possible. You must install .NET runtime to run any .NET program.

Q33: 在搜尋欄或行時,能否把這些欄或行highlight起來以方便檢視?
A: What control are you using? We will process while receive your further information.
Q34: 如可做出如xp程式集的選單,VB .NET連SQL的方式好像比之前不易,請問有何方式可將資料庫資料顯示出來呢,還有如何將開發好 的VB .NET執行檔,在另一台沒有灌.NET程式的電腦執行
A:

1.You can use ADO.NET to do this job. Have you tried the GotDotNet samples at http://www.gotdotnet.com/ . You can also search MSDN for ADO.NET.

313483 INFO: Roadmap for ADO.NET DataAdapter Objects http://support.microsoft.com/?id=313483 313480 INFO: Roadmap for .NET Data Providers http://support.microsoft.com/?id=313480

2.This is not possible. You must install .NET runtime to run any .NET program.

Q35: 要如何使用內部的應用程式或功能(目前使用VB .NET)將winxp 宜接關機呢?
A: 目前.NET Framework並未內建此功能,您可以呼叫Win32 API(ExitWindowsEx)。
Q36: datagrid的大小可否進行更改嗎?如原先設定為100,後來想 改為110,可以嗎
A: 更改 Size 屬性(Width, Height)即可
Q37:

在ASP.NET中 ,要如何把整個page都cache下來呢?我的目的是讓user連到這個page的速度可以快一些,因為我們很多的page去資料庫撈資料的時間都很長 ,所以才想使用這樣的方法

我是有找到一個東西如下: <%@ OutputCache Duration="300" VaryByParam="*" %> 是不是只要這樣就可以呢?還是一定要使用Cache.Add()或Cache.Insert()呢?

A: <%@ OutputCache Duration="300" VaryByParam="*" %> 只要這樣就可以 Cache.Add()或Cache.Insert()跟你的需求不同
Q38: 在 Win Form DataGrid 的欄位標題上按一下可以執行排序的動作,那有無任何方法可以針對DataGrid執行多欄的排序?
A: Write code by yourself or buy 3party usercontrol
Q39: 是否有人能告訴我在VS.NET中可不可以進行winform的debug
A: Of course!
Q40: 在Combobox中允許存在多個columns嗎
A:

This is a simple example of how to display table values(ie multiple columns) in a combobox. For the dropdown window, a form with a listview docked to fill can be used. The MultiColumnCombobox class is inherited from the System.Windows.Forms.Combobox class.

protected override void OnDropDown(System.EventArgs e){ Form parent = this.FindForm(); if(this.dataTable != null || this.dataRows!= null){ MultiColumnComboPopup popup = new MultiColumnComboPopup(this.dataTable,ref this.selectedRow,columnsToDisplay); popup.AfterRowSelectEvent+=new AfterRowSelectEventHandler(MultiColumnComboBox_AfterSelectEvent); popup.Location = new Point(parent.Left + this.Left + 4 ,parent.Top + this.Bottom + this.Height); popup.Show(); .......................... The OnDropDown event of the ComboBox is overriden to display our popup from. The popup form should never be a modal, because the popup has to close if the user decides to click elsewhere other than the grid on the dropdown form. To check where the user has selected something, I use the "popup.AfterRowSelectEvent" to fire an event on the MulticolumnComboBox. To use the MulticolumnComboBox do the following:

multiColumnComboBox1.Table = dtable;//DataTable multiColumnComboBox1.DisplayMember = "Band";//Column to display after selection multiColumnComboBox1.ColumnsToDisplay = new string[]{"Band","Song","Album"};//columns to display //in the dropdown grid After the DataTable is assigned to the combo, the dropdown looks like this:

After Selection, the DisplayMember of that row is displayed.

Q41:

<select name="Test"> <option value="A">台北 <option value="B">新竹 <option value="C">台中 </select>

ASP.NET是否有替代的元件呢?如何做Data Binding??

A: <asp:dropdownlist id="ddl地區" runat="server"> <asp:ListItem Value="A">台北</asp:ListItem> <asp:ListItem Value="B">新竹</asp:ListItem> <asp:ListItem Value="C">台中</asp:ListItem> </asp:dropdownlist>
Q42: 是否可以針對一個 Label 之內的文字設定一種以上的顏色?
A: 目前的版本不支援這項功能。
Q43: How can I put a form in Systray whenever I close that?
A: You can use NotifyIcon control to provide this function。
Q44: 以往可用VB或ASP使用RDS存取TCP/IP遠端DATABASE一旦連線成功後希望在連線這段時間內能不斷的獲得及時資料的更新 ,因整体網 路(包含SERVER & CLIENT)DELAY的不確定性,以往使用笨方法:於CLIENT端以interval=1 second初始值 ,定周期作(RDS)request,一但發現於周期時間內沒收到server端respons,則將terval 增加一秒鐘,依此類推,以推測追蹤最佳delay通訊時間. 請問於ado.net領域有何較佳solution?
A: You can use SQL Server Notification Services
Q45: 我要如何衡量scrollbar的寬度,還有,這個寬度可以自行設定嗎
A:

This setting is system-wide. Once you change it, all the windows that have scrollbars will be affected. if you do want to do this, you may need to use some Win32 API function.

http://msdn.microsoft.com/library/en-us/dnvbadev/html/chapter9retrievingsettingsysteminformation.asp  

Q46: 不知怎麼了,我的winform視窗竟然無法關閉(按視 窗右上角的x符號關不起來
A: 是當機了嗎?還是被程式設定住了?
Q47: 我想讓form可隨著內容改變大小,不知能不能做到
A:

public void AutoSizeCol(int col)

{float width = 0;

int numRows = ((DataTable) dataGrid1.DataSource).Rows.Count;

Graphics g = Graphics.FromHwnd(dataGrid1.Handle);

StringFormat sf = new StringFormat (StringFormat.GenericTypographic);

SizeF size;

for(int i = 0; i < numRows; ++ i)

{ size = g.MeasureString(dataGrid1[i, col].ToString (), dataGrid1.Font, 500, sf);

if(size.Width > width)

width = size.Width; }

g.Dispose();

dataGrid1.TableStyles["customers"].GridColumnStyles [col].Width = (int) width + 8; // 8 is for leading and trailing padding }

Q48: win DataSet 在不指定欄位名稱下,能不能讓 dateTime 像 web DataSet 一樣自動顯示日期及時間,而不是僅顯示日期?
A: 這應該是一樣的。你是怎麼做的呢?在WinForm 和在 WebForm 中,你用的是相同的代碼嗎?
Q49: 我在 Win Form 建立一個 ToolBar 的元件之後,接著拉一個 ImageList 元件進來,在 Image Collection Editor 畫面中,按 Add 按鈕,出現開啟對話方塊,要我選擇 Image File,請問一般 Window 應用程式常用的工具列圖片(如 :Open, Save, Print...)是存放在C:\ 那一個資料夾之下?
A: 您可以在Visual Studio.NET的安裝路徑下找到這些東西。 C:\Program Files\Microsoft Visual Studio .NET\Common7\Graphics\bitmaps\...
Q50: 在datagrid中的顏色是不是像一般我們使用的顏色的代碼去 code就行了?
A: 可以到屬性中更改, 當然,如果要在程式碼中去設定也行
Q51: 在VB .NET中要如何設定WS_EX_LAYERED?
A:

VB and VB.NET include transparency properties that allow a window to pass mouse events to the window below it. This action is useful when you're using transparent windows. By passing mouse events, the transparent window doesn't impede the user from interacting with windows beneath it.

In Visual Basic 6, set the window’s WS_EX_TRANSPARENT attribute, which controls the window’s style. This is done through the SetWindowLong API call, as you can see in Listing D.

The code in the Command1_Click event in Listing E shows how to make a window pass through mouse events.

To reverse the transparency, reset the WS_EX_TRANSPARENT attribute as shown in Listing F, which will remove the window.

Be forewarned that setting the WS_EX_TRANSPARENT attribute affects the entire window; the user can't close the window, select it with the mouse, or select any controls on the form. The application can still close the window programmatically. You could use such a transparent window for a heads-up display of important data.

With .NET, you can use the form’s TransparencyKey property. Set this property to the color you want to be transparent. The code in Listing G sets the transparency of the form to its background color.

Using .NET's TransparencyKey property gives slightly different results than VB 6's WS_EX_TRANSPARENT style. .NET's TransparencyKey makes the client area of the window visually transparent as well as transparent to mouse events. However, it leaves controls and the window title bar selectable. Obviously, this level of control has far more applications than simply disabling a window entirely. Setting the window to pass through mouse events enables you to display information to your users while allowing them to select forms below the transparent window.

Q52:

有沒有辦法在ASP.NET中做到讓server 在固定的時間(例如每十分鐘)將網頁cook好讓使用者連到這個page的時候已經是cache的資料了

A: 系統並未內建此種功能,不過有個變通的方式,您可以寫一個Windows Service定期組 好所要的HTML頁面(自行透過HTTP協定呼叫該ASPX,再將內容存成HTML檔案)讓前端存取。
Q53: 哪裡有文件能找到如何使用store procedure
A:

預存程序對資料驅動應用程式有許多好處。使用預存程序,資料庫作業可以封裝在單一 命令中、最佳化為最佳效能,並且可進一步提升安全性。您只要將預存程序名稱後接參數引數 (類似 SQL 陳述式) 再傳遞出去,即可呼叫預存程序。而使用 ADO.NET Command 物件的 Parameters 集合,您可以更準確地定義預存程序參數、存取輸出參數 並傳回值。 若要呼叫預存程序,請將 Command 物件的 CommandType 屬性設定為 StoredProcedure。一旦 CommandType 設定為 StoredProcedure 後,您就可以使用 Parameters 集合來定義參數,如下列範例所示。 SqlClient [Visual Basic] Dim nwindConn As SqlConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;" & _ "Initial Catalog=northwind")

Dim salesCMD As SqlCommand = New SqlCommand("SalesByCategory", nwindConn) salesCMD.CommandType = CommandType.StoredProcedure

Dim myParm As SqlParameter = salesCMD.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15) myParm.Value = "Beverages"

nwindConn.Open()

Dim myReader As SqlDataReader = salesCMD.ExecuteReader()

Console.WriteLine("{0}, {1}", myReader.GetName(0), myReader.GetName(1))

Do While myReader.Read() Console.WriteLine("{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)) Loop

myReader.Close() nwindConn.Close()[C#] SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");

SqlCommand salesCMD = new SqlCommand("SalesByCategory", nwindConn); salesCMD.CommandType = CommandType.StoredProcedure;

SqlParameter myParm = salesCMD.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15); myParm.Value = "Beverages";

nwindConn.Open();

SqlDataReader myReader = salesCMD.ExecuteReader();

Console.WriteLine("{0}, {1}", myReader.GetName(0), myReader.GetName(1));

while (myReader.Read()) { Console.WriteLine("{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)); }

myReader.Close(); nwindConn.Close();OleDb [Visual Basic] Dim nwindConn As OleDbConnection = New OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;" & _ "Initial Catalog=northwind")

Dim salesCMD As OleDbCommand = New OleDbCommand("SalesByCategory", nwindConn) salesCMD.CommandType = CommandType.StoredProcedure

Dim myParm As OleDbParameter = salesCMD.Parameters.Add("@CategoryName", OleDbType.VarChar, 15) myParm.Value = "Beverages"

nwindConn.Open()

Dim myReader As OleDbDataReader = salesCMD.ExecuteReader()

Console.WriteLine("{0}, {1}", myReader.GetName(0), myReader.GetName(1))

Do While myReader.Read() Console.WriteLine("{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)) Loop

myReader.Close() nwindConn.Close()[C#] OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;" + "Initial Catalog=northwind");

OleDbCommand salesCMD = new OleDbCommand("SalesByCategory", nwindConn); salesCMD.CommandType = CommandType.StoredProcedure;

OleDbParameter myParm = salesCMD.Parameters.Add("@CategoryName", OleDbType.VarChar, 15); myParm.Value = "Beverages";

nwindConn.Open();

OleDbDataReader myReader = salesCMD.ExecuteReader();

Console.WriteLine("\t{0}, {1}", myReader.GetName(0), myReader.GetName(1));

while (myReader.Read()) { Console.WriteLine("\t{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)); }

myReader.Close(); nwindConn.Close();Parameter 物件可透過 Parameter 建構函式來建立,也可由呼叫 Command 所屬的 Parameters 集合的 Add 方法來建立。Parameters.Add 會把建構函式 引數或現有 Parameter 物件當成輸出。要將 Parameter 的 Value 設定為 Null 參考 時,請使用 DBNull.Value。 除了輸入參數以外的參數,您必須設定 ParameterDirection 屬性,以將參數型別指定 為 InputOutput、Output 或 ReturnValue。下列範例顯示建立 Input、Output 和 ReturnValue 參數間的不同。 SqlClient [Visual Basic] Dim sampleCMD As SqlCommand = New SqlCommand("SampleProc", nwindConn) sampleCMD.CommandType = CommandType.StoredProcedure

Dim sampParm As SqlParameter = sampleCMD.Parameters.Add("RETURN_VALUE", SqlDbType.Int) sampParm.Direction = ParameterDirection.ReturnValue

sampParm = sampleCMD.Parameters.Add("@InputParm", SqlDbType.NVarChar, 12) sampParm.Value = "Sample Value"

sampParm = sampleCMD.Parameters.Add("@OutputParm", SqlDbType.NVarChar, 28) sampParm.Direction = ParameterDirection.Output

nwindConn.Open()

Dim sampReader As SqlDataReader = sampleCMD.ExecuteReader()

Console.WriteLine("{0}, {1}", sampReader.GetName(0), sampReader.GetName(1))

Do While sampReader.Read() Console.WriteLine("{0}, {1}", sampReader.GetInt32(0), sampReader.GetString(1)) Loop

sampReader.Close() nwindConn.Close()

Console.WriteLine(" @OutputParm: {0}", sampleCMD.Parameters("@OutputParm").Value) Console.WriteLine("RETURN_VALUE: {0}", sampleCMD.Parameters("RETURN_VALUE").Value)[C#] SqlCommand sampleCMD = new SqlCommand("SampleProc", nwindConn); sampleCMD.CommandType = CommandType.StoredProcedure;

SqlParameter sampParm = sampleCMD.Parameters.Add("RETURN_VALUE", SqlDbType.Int); sampParm.Direction = ParameterDirection.ReturnValue;

sampParm = sampleCMD.Parameters.Add("@InputParm", SqlDbType.NVarChar, 12); sampParm.Value = "Sample Value";

sampParm = sampleCMD.Parameters.Add("@OutputParm", SqlDbType.NVarChar, 28); sampParm.Direction = ParameterDirection.Output;

nwindConn.Open();

SqlDataReader sampReader = sampleCMD.ExecuteReader();

Console.WriteLine("{0}, {1}", sampReader.GetName(0), sampReader.GetName(1));

while (sampReader.Read()) { Console.WriteLine("{0}, {1}", sampReader.GetInt32(0), sampReader.GetString(1)); }

sampReader.Close(); nwindConn.Close();

Console.WriteLine(" @OutputParm: {0}", sampleCMD.Parameters["@OutputParm"].Value); Console.WriteLine("RETURN_VALUE: {0}", sampleCMD.Parameters["RETURN_VALUE"].Value);OleDb [Visual Basic] Dim sampleCMD As OleDbCommand = New OleDbCommand("SampleProc", nwindConn) sampleCMD.CommandType = CommandType.StoredProcedure

Dim sampParm As OleDbParameter = sampleCMD.Parameters.Add("RETURN_VALUE", OleDbType.Integer) sampParm.Direction = ParameterDirection.ReturnValue

sampParm = sampleCMD.Parameters.Add("@InputParm", OleDbType.VarChar, 12) sampParm.Value = "Sample Value"

sampParm = sampleCMD.Parameters.Add("@OutputParm", OleDbType.VarChar, 28) sampParm.Direction = ParameterDirection.Output

nwindConn.Open()

Dim sampReader As OleDbDataReader = sampleCMD.ExecuteReader()

Console.WriteLine("{0}, {1}", sampReader.GetName(0), sampReader.GetName(1))

Do While sampReader.Read() Console.WriteLine("{0}, {1}", sampReader.GetInt32(0), sampReader.GetString(1)) Loop

sampReader.Close() nwindConn.Close()

Console.WriteLine(" @OutputParm: {0}", sampleCMD.Parameters("@OutputParm").Value) Console.WriteLine("RETURN_VALUE: {0}", sampleCMD.Parameters("RETURN_VALUE").Value)[C#] OleDbCommand sampleCMD = new OleDbCommand("SampleProc", nwindConn); sampleCMD.CommandType = CommandType.StoredProcedure;

OleDbParameter sampParm = sampleCMD.Parameters.Add("RETURN_VALUE", OleDbType.Integer); sampParm.Direction = ParameterDirection.ReturnValue;

sampParm = sampleCMD.Parameters.Add("@InputParm", OleDbType.VarChar, 12); sampParm.Value = "Sample Value";

sampParm = sampleCMD.Parameters.Add("@OutputParm", OleDbType.VarChar, 28); sampParm.Direction = ParameterDirection.Output;

nwindConn.Open();

OleDbDataReader sampReader = sampleCMD.ExecuteReader();

Console.WriteLine("{0}, {1}", sampReader.GetName(0), sampReader.GetName(1));

while (sampReader.Read()) { Console.WriteLine("{0}, {1}", sampReader.GetInt32(0), sampReader.GetString(1)); }

sampReader.Close(); nwindConn.Close();

Console.WriteLine(" @OutputParm: {0}", sampleCMD.Parameters["@OutputParm"].Value); Console.WriteLine("RETURN_VALUE: {0}", sampleCMD.Parameters["RETURN_VALUE"].Value);使用參數配合 SqlCommand 使用參數配合 SqlCommand 時,加入 SqlParameterCollection 的參數名稱必須與預存 程序內參數標記的名稱相符。SQL Server .NET 資料提供者會將預存程序內的參數視為 具名參數,並搜尋相符的參數標記。 SQL Server .NET 資料提供者不支援以問號 (?) 替代符號 (Placeholder) 來傳遞參數 至 SQL 陳述式或預存程序。這種情況下,您必須使用具名參數,如下列範例所示。 SELECT * FROM Customers WHERE CustomerID = @CustomerID使用參數配合 OleDbCommand 使用參數配合 OleDbCommand 時,加入 OleDbParameterCollection 的參數名稱必須與 預存程序內參數標記的名稱相符。OLE DB .NET 資料提供者會將預存程序內的參數視為 具名參數,並搜尋相符的參數標記。 OLE DB .NET 資料提供者不支援以具名參數來傳遞參數至 SQL 陳述式或預存程序。這 種情況下,您必須使用問號 (?) 替代符號,如下列範例所示。 SELECT * FROM Customers WHERE CustomerID = ?所以,Parameter 物件加入 Parameters 集合的順序必須直接對應至參數問號替代符號的位置。 衍生參數資訊 您也可以使用 CommandBuilder 類別從預存程序衍生參數。SqlCommandBuilder 和 OleDbCommandBuilder 類別均提供靜態方法 DeriveParameters,該方法會自動將來自 預存程序的參數資訊填入 Command 物件的 Parameters 集合。請注意, DeriveParameters 將會覆寫 Command 所有的現有參數資訊。 衍生參數資訊需要加入至資料來源的存取作業,以取得資料。若在設計階段已知參數資 訊,您便可以明確設定參數,改善應用程式的效能。 下列程式碼範例顯示如何使用 CommandBuilder.DeriveParameters 填入 Command 物件 的 Parameters 集合。 [Visual Basic] Dim nwindConn As SqlConnection = New SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;") Dim salesCMD As SqlCommand = New SqlCommand("Sales By Year", nwindConn) salesCMD.CommandType = CommandType.StoredProcedure

nwindConn.Open() SqlCommandBuilder.DeriveParameters(salesCMD) nwindConn.Close()[C#] SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;"); SqlCommand salesCMD = new SqlCommand("Sales By Year", nwindConn); salesCMD.CommandType = CommandType.StoredProcedure;

nwindConn.Open(); SqlCommandBuilder.DeriveParameters(salesCMD); nwindConn.Close();

Q54: I want to know that how to add propertytab to property grid.
A: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/usingpropgrid.asp
Q55: 我想知道如何更改tooltip字體顏色
A: I'm afraid no unless you create your own Tooltip class.
Q56: 最近到網路上及書店想找一些XML程式設計開發資訊及書籍? 卻沒有什收穫!希望能看到有更多的資訊與大家分享!
A: 有一些好書,您可試著找英文書籍
Q57: DateTimePicker 與 MonthCalendar 這2個元件用法上有何不同?
A: By the manual:MonthCalendar 控制項允許使用者使用視覺化顯示來選取日期和時 間。您可以設定 MinDate 和 MaxDate 屬性,來限制能夠選取的日期和時間。 您可以設定 ForeColor 、 Font 、 TitleBackColor 、 TitleForeColor 、 TrailingForeColor 和 BackColor 屬性,來變更控制項月曆部份的外觀。 如果須自訂日期格式,而且選取範圍限制為只有一個日期,您可能 會考慮使用 DateTimePicker 控制項,不用 MonthCalendar 。使 用 DateTimePicker 可免除驗證日期時間值的大半需求。
Q58: 如果只想讓client能在datagrid編輯,但無法增加新列的話,要如何設定
A: Datagrid不要加入新增按鈕
Q59: 不知道動態圖檔是否能放在winform中,那有沒有什麼要特別設定的
A: No. You need to find a control that supports gif.
Q60: 我原先設計的form,約20k,但是後來執行時,這個檔卻變的很大,約30MB,我想知道為什麼會這樣呢
A: 因為在執行期必須同時載入其他檔案(例如:使用到的.NET Framework Library)才能運作,所以檔案大小跟所佔用的記憶體原本就不會相同,您遇到的狀況是正常的。
Q61: toolbar可以設成動態的嗎
A: 設定權限,就可以讓toolbar依不同的user有不同的資料,不過要加入多個toolbar 
Q62: 在VS.NET中還有沒有coolbar?
A: No
Q63: 如果我要把listviewitems(圖示顯示),在 listview中移除,該怎麼做
A: 使用ListViewObj.Items.Remove(listviewitemObj)。
Q64: How do I disable a PropertyGrid item at runtime?
A: Does this article help? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/usingpropgrid.asp
Q65: 如果不需要title bar,border的話,只要form就好了,那client可以就只看到form嗎
A: 將FormBorderStyle屬性改成None即可。
Q66: 我知道在vb6,可以告訴你說這是誰的form,請問這個在VB .NET也可以做到嗎
A:

How did you do in VB6? FindWindow?

If so, you also need FindWindow to find the window in VB.NET

Q67: 在Windows.Forms.Datagrid中的列的高度可以改變嗎
A: RowResize The row border, which is the line between grid row headers. It can be dragged to resize a row's height.
Q68: 我想知道在tabcontrol中的tabpage背景顏色能不能更改
A: 例如:this.tabPage1.BackColor = System.Drawing.Color.Red;
Q69: 有沒有較快速的方式可以把form refresh
A: FormName.Refresh()
Q70: 如果我想一點form A的button時,會開啟form B,可以做的到嗎
A: 假設第2個Form的Class為Form2,使用下列程式片斷即可: Dim myForm2 As New Form2() myForm2.Show()
Q71: 由於公司需要,想要把run time中的語言改成和目前使用的 VB .NET application中不一樣的語言,請問,能不能改?那要在哪裡改
A: 一般而言編譯過後的檔案(DLL與EXE)可運作在不同語系的.NET Framework。
Q72: 我想知道有沒有方法在當滑鼠移到某個label control的 時候,會出現這個label control的小秘訣或說明
A: 您可以使用 tooltip 控制項。 您可以在 Windows Form 的工具箱中找到!
Q73: 在MDI frame中,要如何讓scroll bar 不要出現?
A: In Form_Load Me.VScroll = False Me.HScroll = False
Q74: 為何無法將ProgressBar在StatusBarPanel中顯示出來
A:

class MyApp : Form { ProgressBar pbar = new ProgressBar(); StatusBarPanel ProgressPanel = new StatusBarPanel();

public MyApp() { StatusBar sb = new StatusBar(); sb.Parent = this; sb.ShowPanels = true;

StatusBarPanel panel1 = new StatusBarPanel(); panel.AutoSize = StatusBarPanelAutoSize.Contents; panel.Text = "Mein Text"; sb.Panels.Add(panel);

ProgressPanel .AutoSize = StatusBarPanelAutoSize.Spring; sb.Panels.Add(ProgressPanel );

pbar.Value = 30; pbar.Parent = sb; pbar.Width = ProgressPanel .Width; pbar.Location = new Point(panel1.Width, 0); }

protected override void ONResize(EventArgs ea) { base.OnResize(ea); pbar.Width = ProgressPanel.Width; } }

Q75: .NET的control可以放在MFC的application嗎?
A: 目前應該沒有辦法做到這件事。
Q76: 好像有一個功能是可以不要讓視窗關閉的,就是儘管使用者點選了視窗右上方的x符號也不能關閉視窗,請問要怎麼做
A: 將Form屬性的MinimizeBox設定成False試試
Q77: 在winform建立後能更改它的類別樣式嗎?
A: No
Q78: 在browser component中可以設proxy嗎
A: WebBrowser 沒有這個功能,可以設法在應用程式中設置Proxy,更詳細資料請查MSDN,如:
http://msdn.microsoft.com/library/en-us/office97/html/usingwebbrowsercontrol.asp?frame=true
Q79: 在mainmenu的背景顏色要如何改呢?
A:

Sample list below

using System; using System.Windows.Forms; using System.Drawing;

///<Summary> ///This application demonstrates how to create Menus at runtime. ///</Summary>

class RuntimeMenus:Form { private MainMenu myMenu; private MenuItem mnuFile, mnuExit, mnuRtime; private Button btnAdd, btnRemove, btnClose; private Graphics g; private Font DispFont; private SolidBrush MyBrush; static int i;

///Constructor Calls InitializeComponents method, which is used ///for initializing components that are used in the application

public RuntimeMenus() { InitializeComponents(); }

public void InitializeComponents() { DispFont = new Font("Verdana",8,FontStyle.Bold); MyBrush = new SolidBrush(Color.Blue);

//Instantiating Main Menu myMenu = new MainMenu();

//Instantiating Menus mnuFile = new MenuItem("&File"); mnuRtime = new MenuItem("&Runtime Menu");

//Adding menus to Main Menu myMenu.MenuItems.Add(mnuFile); myMenu.MenuItems.Add(mnuRtime);

//Instantiating Exit menuitem along with a shortcut key. mnuExit = new MenuItem("&Exit", new EventHandler(btnClose_Click), Shortcut.CtrlX); //Adding menuitem to File Menu mnuFile.MenuItems.Add(mnuExit);

//Instantiating Add Button btnAdd = new Button(); btnAdd.Location = new Point(275,20); btnAdd.Text = "&Add"; btnAdd.Click += new EventHandler(btnAdd_Click); btnAdd.Size = new Size(100,30);

//Instantiating Remove Button btnRemove = new Button(); btnRemove.Location = new Point(275,60); btnRemove.Text = "&Remove"; btnRemove.Click += new EventHandler(btnRemove_Click); btnRemove.Size = new Size(100,30);

//Instantiating Close Button btnClose = new Button(); btnClose.Location = new Point(275,100); btnClose.Text = "&Close"; btnClose.Click += new EventHandler(btnClose_Click); btnClose.Size = new Size(100,30);

//Adding Buttons to Form this.Controls.Add(btnAdd); this.Controls.Add(btnRemove); this.Controls.Add(btnClose);

//Setting properties of the Form this.MaximizeBox = false; this.MinimizeBox = false; this.Text = "Creating Menus on the Fly"; this.Menu = myMenu; this.Size = new Size(400,250); this.CancelButton = btnClose; this.StartPosition = FormStartPosition.CenterScreen;

//Initializing Graphics from Windows Handle g = Graphics.FromHwnd(this.Handle); }

///Adds Menuitems to RuntimeMenu protected void btnAdd_Click(object sender, EventArgs e) { mnuRtime.MenuItems.Add("Runtime Menu " + (i+1), new EventHandler(mnuRtime_Click)); g.Clear(Color.FromArgb(214,211,206)); g.DrawString("Runtime Menu " + (i + 1) + " added Successfully",DispFont,MyBrush,50,150); i++; }

///Removes Menuitems from RuntimeMenu protected void btnRemove_Click(object sender, EventArgs e) { if (i <= 0) { g.Clear(Color.FromArgb(214,211,206)); g.DrawString("Menu is Empty",DispFont, MyBrush,125,150); } else { mnuRtime.MenuItems.RemoveAt(i-1); g.Clear(Color.FromArgb(214,211,206)); g.DrawString("Runtime Menu " + (i) + " Removed Successfully",DispFont,MyBrush,50,150); i=i-1; } }

///Event for Displaying the MessageBox on Clicking protected void mnuRtime_Click(object sender, EventArgs e) { String s = sender.ToString(); MessageBox.Show("You Clicked " + s.Substring(51), "RunTime Menu",MessageBoxButtons.OK, MessageBoxIcon.Information); }

///Event for Closing Window protected void btnClose_Click(object sender, EventArgs e) { Application.Exit(); }

///Instantiating the Application public static void Main() { Application.Run(new RuntimeMenus()); } }

Q80: 滑鼠指標的顏色能不能換
A: Please refer to http://support.microsoft.com/default.aspx?scid=kb;en-us;267849
Q81: 用c可以去寫收信的程式嗎(在winform中)
A: No. You need Visual C++.NET because you don't have a .NET Runtime support for C language.
Q82: can someone tell me how to append a new Form with an existing assembly?
A: Assembly is a unit of deployment in .NET term.
Q83: 如果我想在windows form中確認哪些IP是可用的,請問要怎麼做
A: you may want to look at the System.Net.Sockets namespace.
Q84: 若DataSet有兩個Data Table,可以將兩個Data Table的資料join,新增到一個新的Data Table中 嗎?ps:因為當讀到Data Table的資料時,count會減少一筆,所以Data Table的資料就少了一筆
A: Pls refer to HOW TO: Implement a DataSet JOIN helper class in Visual C# .NET http://support.microsoft.com/?id=326080 
Q85: 想寫一個算出今天是第幾週的函數,但發現 DatePart("ww",Input_Day,0,FirstWeekOfYear.Jan1) 正常, DatePart("ww",Input_Day,1,FirstWeekOfYear.Jan1), >> DatePart >> ("ww",Input_Day,FirstDayOfWeek.Monday,FirstWeekOfYear.Jan1) >> and DatePart("ww",Input_Day,0,2)指令都會失敗,是否有別的解法呢?(FirstDayOfWeekValue希望能自行設定)
A: What problem at your side now? We will process while receive your further information.
posted on 2005-03-12 13:32  James Wong   阅读(3444)  评论(0)    收藏  举报