2009-08-12 60 views
0

我有我創建後面代碼訪問控制以JavaScript

Dim txtdate1 As New TextBox 
    txtdate1.ID = "txtdate1" 
    cell.Controls.Add(txtdate1) 

細胞爲i添加到一個gridview一個標題表單元格的控制。

我需要訪問這個在JavaScript

var txtdate1 = document.getElementById('txtdate1'); 

OR

var txtdate1 = document.getElementById('<%=txtdate1.clientID'); 

如何才能做到這一點?

這是細胞如何創建

Dim cell As New TableCell 
Dim row As New GridViewRow(-1, -1, DataControlRowType.Separator, DataControlRowState.Normal) 
    row.BackColor = System.Drawing.ColorTranslator.FromHtml("#B5C7DE") 
    row.ForeColor = Drawing.Color.White 
    If GridView1.Rows.Count <> 0 Then 
     GridView1.Rows(0).Parent.Controls.AddAt(0, row) 
    Else 

    End If 

    row.Controls.Add(labelcell) 
    row.Cells.Add(cell) 

回答

0

您應該能夠使用內置的與客戶端ID結合MS阿賈克斯$find功能。

var txtdate1 = $find('<%=txtdate1.ClientID %>'); 
+0

我收到以下內容: 名稱'txtdate1'未聲明 – Eric 2009-08-12 16:27:51

+0

錯誤是正確的,因爲控件未在頁面上聲明。你在這裏處理動態控制,所以你需要做一個動態查找。 – Yona 2009-08-12 16:38:47

+0

@Y Low-如何在這種情況下使用動態查找?我從來沒有聽說過它。 – Eric 2009-08-12 16:47:03

1

嘗試:

var txtdate1 = $find('<%= cell.FindControl("txtdate1").ClientID %>'); 

或者當你在代碼中動態創建的控制,客戶端ID保存到頁面的一個屬性,然後渲染性能。

首先創建一個類的屬性:

Dim txtID As String  'This should be a class property 

然後當你動態創建的控制,節省客戶端ID:

Dim txtdate1 As New TextBox 
txtdate1.ID = "txtdate1" 
cell.Controls.Add(txtdate1) 
Me.txtID = txtdate1.ClientID 'Save the client id to a property 

然後在JavaScript可以加載這樣的控制:

var txtdate1 = $find('<%= txtID %>'); 
+0

與此問題是該單元格是動態創建的! 我會再次編輯我的問題。 – Eric 2009-08-12 17:06:51

+0

然後只是使用一個頁面變量來保存ClientID,(我的答案的第二部分) – Yona 2009-08-12 17:10:40

+0

我現在得到這個錯誤: '... txtid'在這個上下文中是不可訪問的,因爲它是'Private'。 – Eric 2009-08-12 17:18:36

-1

你已經差不多了。其實,如果你的第二行可以編譯,我感到很驚訝。

var txtdate1 = document.getElementById('<%= cell.FindControl("txtdate1").ClientID %>'); 

順便說一下,夥計們,Javascript和jquery之間有區別,而OP從來沒有表明過jQuery的存在。

+0

這個問題是單元格是動態創建! 我會再次編輯我的問題。 – Eric 2009-08-12 16:59:31

+0

只有你已經指出了jquery的存在... – 2009-08-12 17:13:36

+0

我指的是其他兩個答案,它用$ find代替原生函數。 – harpo 2009-08-12 17:46:48