2008年7月23日 星期三

如何在執行階段指定SQLDataSource的參數值?

Q: SQLDataSource的SQL指令可以指定參數, 並繫結控制項、session、cookie或Query String值, 不幸的是要指定的變數值非以上任何一種, 應如何在執行階段指定參數值?

A: 很簡單, 只要在SqlDataSource1_Selecting 或其他 -ing的事件中指定即可, 例如下例, 指定參數userid值為login的用戶代號:
e.Command.Parameters("@userid").Value = User.Identity.Name

** 切不可使用
SqlDataSource1.SelectCommand &= " where userid = '" & User.Identity.Name & "'"

2008年7月20日 星期日

變數轉型的三種指令

Q: 我們常要在執行時期使用 FindControl 抓取某一控制項的屬性, 在存取屬性時須先轉換變數, 應該如何處理?

A: 轉換變數有三種方法:
1. CType
Ctype(obj, TextBox).Text --> 將 obj 轉為TextBox型態, 並取得Text屬性值
2. DirectCast, 参數與CType相同, 效率較佳, 但原始型別必須與欲轉換的型別完全相同, 縮小也不可。

3. TryCast, 参數與CType相同, 差別是轉換失敗也不會產生錯誤(exception), 只會將obj設為nothing。

2008年7月10日 星期四

response.redirect 不可出現在try...catch 中

Tips:response.redirect 不可出現在try...catch 中

response.redirect 會產生 exception, 而出現靈異現象, 例如

Try
...
connection1.Close()
Response.Redirect("CompanyGroup1.aspx")
Catch ex As Exception
Try : objTransaction.Rollback() : Catch : End Try
AlertMessage(Replace(Replace(Replace(ex.Message, """", ""), "'", ""), vbNewLine, "")) : Exit Sub
End Try

2008年7月3日 星期四

自動調整ComboBox寬度

Q:如何自動調整ComboBox寬度, 使其下拉自動展為最適合寬度?

A:加一ComboBox事件如下
Private Sub ComboBox1_DropDown(ByVal sender As Object, ByVal e As System.EventArgs)_
Handles ComboBox1.DropDown
Dim senderComboBox As ComboBox = DirectCast(sender, ComboBox)
Dim width As Integer = senderComboBox.DropDownWidth
Dim g As Graphics = senderComboBox.CreateGraphics()
Dim font As Font = senderComboBox.Font
Dim vertScrollBarWidth As Integer = _
IIf((senderComboBox.Items.Count > senderComboBox.MaxDropDownItems), _
SystemInformation.VerticalScrollBarWidth, 0)

Dim newWidth As Integer
For Each s As String In DirectCast(sender, ComboBox).Items
newWidth = CInt(g.MeasureString(s, font).Width) + vertScrollBarWidth
If width < width =" newWidth" dropdownwidth =" width" graphics =" senderComboBox.ComboBox.CreateGraphics()