我在GridView中有一个TextBox
和一个Label
。我的问题是,当我更新GridView并且TextBox
为空时,它会删除Label中的数据(这是有意义的)。我的问题是,是否可以保持TextBox
为空并更新而不丢失任何数据?
C#:
Private void Update()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox timeR = GridView1.Rows[i].FindControl("SitUps") as TextBox;
if (timeR.Text.Length < 10)
{
foreach (GridViewRow row in GridView1.Rows)
{
sb.Append("UPDATE bleaTest SET SitUps = '");
sb.Append((row.FindControl("SitUps") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE id = ");
sb.Append(Convert.ToInt32((row.FindControl("ID") as Label).Text));
sb.Append(" ");
}
}
else
{
timeR.Text = "Number is too high!";
foreach (GridViewRow row in GridView1.Rows)
{
sb.Append("UPDATE bleaTest SET SitUps = '");
sb.Append((row.FindControl("SitUps") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE id = ");
sb.Append(Convert.ToInt32((row.FindControl("ID") as Label).Text));
sb.Append(" ");
}
}
}
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
BindData();
}
ASPX:
<asp:TemplateField HeaderText="Sit Ups">
<ItemTemplate>
<asp:TextBox ID="SitUps" runat="server" type="number" Text='<%# Eval("SitUps") %>' EnableViewState="True"></asp:TextBox></div>
</ItemTemplate>
</asp:TemplateField>
答案 0 :(得分:1)
您可以将if (timeR.Text.Length < 10)
更改为if (timeR.Text.Length < 10 and timeR.Text.Length > 0)
答案 1 :(得分:0)
我在这里找到了问题的代码:
StringBuilder sb = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
TextBox tR = row.FindControl("SitUps") as TextBox;
if(tR.Text != "")
{
sb.Append("UPDATE bleaTest SET SitUps = '");
sb.Append((row.FindControl("SitUps") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE id = ");
sb.Append(Convert.ToInt32((row.FindControl("ID") as Label).Text));
sb.Append(" ");
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
BindData();
}
我清理了代码,现在检查文本是否为空并继续更新。
谢谢!