我在从文本框中检索数据时遇到问题。 TextBox 位于 Gridview 中。我尝试调试,它显示我收集文本框值的变量返回 null
或 System.Web.UI.WebControls.TextBox
。
你能帮我找出问题所在吗?
这是后端和gridview的代码
public void Button_Submit_Onclick(object sender, EventArgs e)
{
for (int i = 0; i < GridView2.Rows.Count; i++)
{
//Textbox from Gridview
TextBox txt_field = (TextBox)GridView2.Rows[i].Cells[12].FindControl("txt_Comment");
//Connection string
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
//id of column
int recordid = Convert.ToInt32(GridView2.DataKeys[i].Values[0]);
//checkbox value
CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("CheckBox1");
bool private1 = Convert.ToBoolean(cbox.Checked);
//open connection and creating sqlcommand
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Update DetailCosts set private='" + private1 + "' Komentar='" + txt_field + "' where recordid=" + recordid;
//
cmd.Parameters.AddWithValue("@private1", SqlDbType.Bit).Value = private1;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
cmd.Parameters.AddWithValue("@Komentar", SqlDbType.NChar).Value = txt_field.ToString();
cmd.ExecuteNonQuery();
if (private1==true)
{
//DateTime date = DateTime.Now;
//cmd.CommandText = "Update AprovedCosts set AprovedCosts.AprovalUser = ";
cmd.CommandText = "Update DetailCosts set privateCost=Costs where recordid=" + recordid;
cmd.ExecuteNonQuery();
}
else
{
cmd.CommandText = "Update DetailCosts set privateCost=0 where recordid=" + recordid;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
GridView :
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:TextBox ID="txt_Comment" runat="server" Text='<%# Eval("Komentar") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
最佳答案
为了使它更简单,只需像这样使用它
TextBox txt_field = (TextBox)GridView2.Rows[i].Cells[12].FindControl("txt_Comment");
string txt = txt_field.text; //store it's text in string
并更改命令
代替 txt_field
只需编写 txt 或 txt.ToString();
cmd.CommandText = "Update DetailCosts set private='" + private1 + "' Komentar='" + txt + "' where recordid=" + recordid;
//
cmd.Parameters.AddWithValue("@private1", SqlDbType.Bit).Value = private1;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
cmd.Parameters.AddWithValue("@Komentar", SqlDbType.NChar).Value = txt.ToString();
关于c# - Gridview 中的 TextBox 返回 null 或 'System.Web.UI.WebControls.TextBox',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832060/