简体   繁体   English

C# TextBox.text 返回 null

[英]C# TextBox.text returns null

I am trying to make an editor for a webpage.我正在尝试为网页制作一个编辑器。 However, whenever I try and access the text from my textboxes in a gridview, I receive the error "object reference not set to an instance of an object."但是,每当我尝试从 gridview 中的文本框中访问文本时,我都会收到错误消息“对象引用未设置为 object 的实例”。 My code is as follows.我的代码如下。

 SqlConnection con = new SqlConnection(DatabaseClient.ConnectionString);
            try
            {
            int id = (int)CompoundTable.DataKeys[e.RowIndex].Value;



            TextBox name = CompoundTable.Rows[e.RowIndex].FindControl("name") as TextBox;
                TextBox cat = (TextBox)CompoundTable.Rows[e.RowIndex].FindControl("cation_quantity");
                TextBox catname = (TextBox)CompoundTable.Rows[e.RowIndex].FindControl("cation");
                TextBox an = (TextBox)CompoundTable.Rows[e.RowIndex].FindControl("anion");
                TextBox anName = (TextBox)CompoundTable.Rows[e.RowIndex].FindControl("anion_quantity");
                TextBox diff = (TextBox)CompoundTable.Rows[e.RowIndex].FindControl("difficulty_level");

                con.Open();
                SqlCommand command = new SqlCommand("UPDATE Compound SET compound_name='" + name.Text  + "' WHERE compound_name = @compound",con); //The line that the error is thrown.
                command.Parameters.Add("@compound", SqlDbType.NVarChar, CompoundName.Text.Trim().Length).Value = CompoundName.Text.Trim();
                command.ExecuteNonQuery();
                con.Close();


                CompoundTable.EditIndex = -1;
                BindGridView();
            }
<asp:GridView ID="CompoundTable" runat="server" AllowSorting="True" AllowPaging="True" AutoGenerateColumns="False" PageSize="20" OnSorting="CompoundTable_Sorting" OnPageIndexChanging="CompoundTable_PageIndexChanging" OnRowCancelingEdit="CompoundTable_CancelEdit" OnRowEditing="CompoundTable_Edit" OnRowUpdating="CompoundTable_Update" CellPadding="4">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="Compound" SortExpression="name" />
                    <asp:BoundField DataField="name" HeaderText="Compound" SortExpression="name" />
                    <asp:BoundField DataField="cation" HeaderText="Cation" SortExpression="cation" />
                    <asp:BoundField DataField="cation_quantity" HeaderText="Cation Quantity" SortExpression="cation" />
                    <asp:BoundField DataField="anion" HeaderText="Anion" SortExpression="anion" />
                    <asp:BoundField DataField="ANION_QUANTITY" HeaderText="Anion Quantity" SortExpression="anion" />
                    <asp:BoundField DataField="difficulty_level" HeaderText="Difficulty" SortExpression="difficulty_level" />
                    <asp:HyperLinkField DataNavigateUrlFields="compound_id" DataNavigateUrlFormatString="DeleteCompound.aspx?compound={0}" Text="Delete Compound" />
                     <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="LBEdit" runat="server"  CommandName="Edit" >Edit</asp:LinkButton>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="LBCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                <asp:LinkButton ID="LBUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
            </EditItemTemplate>
        </asp:TemplateField>
                </Columns>
            </asp:GridView>

Look at what CompoundTable.Rows[e.RowIndex].FindControl("name") is returning.查看CompoundTable.Rows[e.RowIndex].FindControl("name")返回的内容。 I don't know webforms too well, but a quick look at the docs shows that BoundField does not inherit from TextBox .我不太了解 webforms,但快速查看文档表明BoundField没有继承自TextBox

When you cast using as , if the cast fails, no exception is thrown, but the returned object is null. You are getting the exception when trying to access the property on the null object.当您使用as进行转换时,如果转换失败,则不会引发异常,但返回的 object 是 null。您在尝试访问 null 上的属性时遇到异常 object。

Because your name.Text is null.因为你的name.Text是null。

If your target is updating the object by clicking the button update, you could do it by doing the following simple way:如果您的目标是通过单击更新按钮来更新 object,则可以通过以下简单方法来完成:

                protected void YourGridIdHere_RowCommand(object sender, GridViewCommandEventArgs e)
                {
                    // If multiple buttons are used in a GridView control, use the
                    // CommandName property to determine which button was clicked.
                    if(e.CommandName=="Your command in CommandName")
                    {
                      // Convert the row index stored in the CommandArgument
                      // property to an Integer.
                      int index = Convert.ToInt32(e.CommandArgument);

                      // Retrieve the row that contains the button clicked 
                      // by the user from the Rows collection.
                      GridViewRow row = YourGridIdHere.Rows[index];

                      // Get data from current selected row.    
                      int ID_COL = 0; 
                      TableCell wantedData = row.Cells[ID_COL];
                      string str = wantedData.Text;

                      // So on....
                }

In form html, you could run it by adding:在表格 html 中,您可以通过添加以下内容来运行它:

OnRowCommand="YourGridIdHere_RowCommand"

to your:给你的:

<asp:GridView ID="CompoundTable" runat="server" AllowSorting="True" AllowPaging="True" AutoGenerateColumns="False" PageSize="20" OnSorting="CompoundTable_Sorting" OnPageIndexChanging="CompoundTable_PageIndexChanging" OnRowCancelingEdit="CompoundTable_CancelEdit" OnRowEditing="CompoundTable_Edit" OnRowUpdating="CompoundTable_Update" CellPadding="4">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM