我在从文本框中检索数据时遇到问题。 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>
答案 0 :(得分:1)
尝试使用txt_field.Text
代替txt_field.ToString()
来获取值。
答案 1 :(得分:1)
您正在搜索可能不存在的控件并将其指定给文本框控件。
TextBox txt_field = (TextBox)GridView2.Rows[i].Cells[12].FindControl("txt_Comment");
为什么不将textbox.text值分配给GridView2.Rows [i] .Cells [12] .Text?
假设它存在,将返回一个值。
答案 2 :(得分:1)
为了使它更简单,只需像这样使用它
TextBox txt_field = (TextBox)GridView2.Rows[i].Cells[12].FindControl("txt_Comment");
string txt = txt_field.text; //store it's text in string
并更改command
代替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();