I Have a TextBox
and a Label
inside of a GridView. My issue is that when I update the GridView and the TextBox
is empty it deletes the data in the Label (which makes sense). My question is, is it possible to keep the TextBox
empty and update without losing any data?
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>
您可以将if (timeR.Text.Length < 10)
和if (timeR.Text.Length < 10 and timeR.Text.Length > 0)
I figured out the issue here's the code:
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();
}
I cleaned up the code and now it checks if the text is not null and proceeds with the update.
Thank you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.