问题
I have a GridView. It has a Checkbox at the beggining, and the other columns are generated automatically:
<asp:GridView ID="DailyData"
EmptyDataText="No data."
CssClass="data-grid"
HeaderStyle-CssClass="HeaderText"
Width="100%"
Visible="true"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
<HeaderStyle Font-Bold="True" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnEdit" OnClick="btnEdit_Click" Text="Editar" runat="server" />
<asp:Button ID="btnSave" OnClick="btnSave_Click" Text="Guardar" runat="server" />
DailyData.AutoGenerateColumns = true;
DailyData.DataSource = dataTable;
DailyData.DataBind();
When I click the "Edit" button, it adds textbox controls in the required cells, and put the cell.text on textbox.text:
protected void btnEdit_Click(object sender, EventArgs e)
{
if (DailyData.Rows.Count > 0)
{
int checks = 0;
foreach (GridViewRow gvr in DailyData.Rows)
{
CheckBox check = gvr.Cells[0].Controls[1] as CheckBox;
if (check.Checked == true)
{
foreach (DataControlFieldCell cell in gvr.Cells)
{
if (!cell.ContainingField.HeaderText.Contains("DATE") &&
!cell.ContainingField.HeaderText.Contains("ID") &&
!cell.ContainingField.HeaderText.Contains("CP") &&
!cell.ContainingField.HeaderText.Equals(""))
{
string texto = cell.Text;
if (texto == " ")
texto = "";
cell.Text = "";
TextBox txt = new TextBox();
txt.Text = texto;
cell.Controls.Add(txt);
}
}
checks++;
}
}
if (checks == 0)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "popup", "alert('There isn't any row checked')", true);
}
}
}
The problem comes when I try to Save the info of those textboxes (which user have edited). When I click the Save button, there aren't any textbox controls in the cells of the GridView.
I've tried to save the GridView into a Session variable just after textboxes are created. And it works, but the problem remains the same... the user's input of those textboxes isn't saved into that Session variable, so when clicking Save button there doesn't exist any textbox.text on them.
Any suggestions on how to do it please?
The Save button's code it's almost the same as Edit button's code, just instead of adding textbox, it would get textbox.text and send to database.
回答1:
Well, I need to get this done before tomorrow, and I ain't found any solution. So that's what I'm going to do, just if it helps somebody in the future.
1) Create a hidden label in the .aspx
2) Create a javascript function that stores every textbox.text into label.value (concatenated)
3) Change Save's button OnClick to OnClientClick="JavaScriptFunction"
4) Create a hidden button in the .aspx with the old Save's button OnClick (the one that calls backend)
5) Click the hidden button at the end of JavaScriptFunction
6) Get data stored from the label in the backend
That's just to avoid the postback.
来源:https://stackoverflow.com/questions/62407397/asp-net-cant-save-changes-from-gridview-to-database