簡體   English   中英

文本框不能在C#ASPX中使用

[英]Textbox can't be used in c# aspx

我在c#(Visual Studio)中使用文本框時遇到問題。 當我寫這篇文章時:

protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = gv.Rows[e.RowIndex];

    TextBox serial = (TextBox)row.Cells[1].Controls[0];
    TextBox name = (TextBox)(row.Cells[2].Controls[0]);
    TextBox cost = (TextBox)(row.Cells[3].Controls[0]);
    TextBox number = (TextBox)(row.Cells[4].Controls[0]);
    string query = String.Format("UPDATE games SET name='{1}', cost={2}, number={4} WHERE serial={0}",
                                serial.Text, name.Text, cost.Text, number.Text);

    SqlConnection connect = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(query, connect);
    connect.Open();
    cmd.ExecuteNonQuery();
    connect.Close();

    this.gv.EditIndex = -1;
    BindTheGridView();
}

我收到這樣的4個錯誤:

錯誤1'TextBox'不包含'Text'的定義,找不到擴展方法'Text'接受類型為'TextBox'的第一個參數(是否缺少using指令或程序集引用?)

有人可以告訴我為什么會這樣嗎? tnx ...

嘗試做這樣的事情:

var serial = (sender as GridView).FindControl("serial") as TextBox;
var name = (sender as GridView).FindControl("name") as TextBox;
...
...

找不到控件的原因是因為您實際上沒有serial文本框等。代碼編譯並執行后,您將擁有與行一樣多的serial文本框。 您可以通過查看呈現頁面的HTML來驗證這一點。 您會在ID /名稱中找到很多帶有serial的文本框

你引用的row ,你有興趣通過調用GridViewRow row = gv.Rows[e.RowIndex]; -這是您將在其中FindControl文本框的行。

因此,嘗試使用以下方法來聯系他們:

TextBox serial = (TextBox)row.FindControl("serial");

等等..

附帶說明一下,gridview中的所有行都將遍歷您的方法; 包括所有頁眉和頁腳。 為確保您不會遇到再次找不到文本框的問題,請指示您的代碼僅在該行實際上是數據行時才進行處理。

因此,包裝您的代碼(獲得GridViewRow之后的代碼, if這樣的if -在獲得row

if (row == GridViewRow.RowType.DataType){
  // your code in here.
}
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = gv.Rows[e.RowIndex];

    string serial = row.Cells[1].Controls[0];
    string name = row.Cells[2].Controls[0]);
    string cost = row.Cells[3].Controls[0]);
    string number = row.Cells[4].Controls[0]);
    yourtextbox_Id.text = serial;
    nametextbox.text = name;
    costtextbox.text = cost ;
    numbertextbox.text = number ;
// do like this

    string query = String.Format("UPDATE games SET name='{1}', cost={2}, number={4} WHERE serial={0}",
                                serial.Text, name.Text, cost.Text, number.Text);

    SqlConnection connect = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(query, connect);
    connect.Open();
    cmd.ExecuteNonQuery();
    connect.Close();

    this.gv.EditIndex = -1;
    BindTheGridView();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM