Anonymous
ASP.NET C#, добавление в GridView с текстовым полем программно, но вторым щелчком мыши замените все данные
Сообщение
Anonymous » 31 окт 2024, 14:37
Мне нужна помощь в реализации функции, позволяющей вводить данные в GridView с текстовыми полями через текстовые поля и DropDownLists. Впоследствии я стремлюсь применять операцию умножения каждый раз при нажатии определенной кнопки. Как только это умножение будет выполнено, я собираюсь отредактировать, если необходимо, представление сетки и выполнить еще одно событие нажатия кнопки, чтобы сохранить измененные данные.
Это разметка .aspx:< /p>
Код, который я пробовал в файле кода программной части C#:
Код: Выделить всё
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using CheckBox = System.Web.UI.WebControls.CheckBox;
using TextBox = System.Web.UI.WebControls.TextBox;
namespace Lista_Tubos_e_Vigas
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string comentario = txtComentario1.Value;
}
protected void Button2_Click(object sender, EventArgs e)
{
string comentario = txtComentario2.Value;
}
protected void Button3_Click(object sender, EventArgs e)
{
string comentario = txtComentario3.Value;
}
protected void Button4_Click(object sender, EventArgs e)
{
string comentario = txtComentario4.Value;
}
protected void Gravar1_click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
SqlCommand command;
SqlDataReader dataReader;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql2, Output = " ";
connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario1.InnerText + "', 'u_ltv1', '', getdate(), '', '', getdate(),''";
command = new SqlCommand(sql2, cnn);
adapter.InsertCommand = new SqlCommand(sql2, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0);
}
command.Dispose();
command.Dispose();
cnn.Close();
//command.ExecuteNonQuery();
string display = Output;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true);
// Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx");
// ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true);
// Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
// ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true);
}
protected void Gravar2_click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
SqlCommand command;
SqlDataReader dataReader;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql2, Output = " ";
connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****";
cnn = new SqlConnection(connetionString);
cnn.Open();
sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario2.InnerText + "', 'u_ltv2', '', getdate(), '', '', getdate(),''";
command = new SqlCommand(sql2, cnn);
adapter.InsertCommand = new SqlCommand(sql2, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0);
}
command.Dispose();
command.Dispose();
cnn.Close();
// command.ExecuteNonQuery();
string display = Output;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true);
// Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx");
// ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true);
// Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
// ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true);
}
protected void Gravar3_click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
SqlCommand command;
SqlDataReader dataReader;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql2, Output = " ";
connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario3.InnerText + "', 'u_ltv3', '', getdate(), '', '', getdate(),''";
command = new SqlCommand(sql2, cnn);
adapter.InsertCommand = new SqlCommand(sql2, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0);
}
command.Dispose();
command.Dispose();
cnn.Close();
// command.ExecuteNonQuery();
string display = Output;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true);
// Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx");
// ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true);
// Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
// ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true);
}
protected void Gravar4_click(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
SqlCommand command;
SqlDataReader dataReader;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql2, Output = " ";
connetionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****";
cnn = new SqlConnection(connetionString);
cnn.Open();
sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario4.InnerText + "', 'u_ltv4', '', getdate(), '', '', getdate(),''";
command = new SqlCommand(sql2, cnn);
adapter.InsertCommand = new SqlCommand(sql2, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0);
}
command.Dispose();
command.Dispose();
cnn.Close();
//command.ExecuteNonQuery();
string display = Output;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true);
//Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx");
//ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true);
//Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
//ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true);
}
protected void Button6_Click(object sender, EventArgs e)
{
//int va = (int)ViewState["valorArmazenado"];
//MessageBox.Show(Convert.ToString(va));
string multiplicador = TextBox4.Text;
//string x_tipo = DropDownList1.SelectedValue;
//string x_pol = DropDownList2.SelectedValue;
//string x_esp = DropDownList3.SelectedValue;
//string x_qual = DropDownList5.SelectedValue;
//string x_medida = TextBox1.Text;
//string x_heatn = TextBox2.Text;
string x_fref = DropDownList4.SelectedValue;
//string x_rec = TextBox3.Text;
int x_nid = 0;
if (GridView1.Rows.Count > 0)
{
string nomeDaColuna = "nid"; // Substitua pelo nome correto da coluna
int columnIndex = -1; // Índice inicial inválido
// Encontre o índice da coluna pelo nome do cabeçalho
for (int i = 0; i < GridView1.Columns.Count; i++)
{
if (GridView1.Columns[i].HeaderText == nomeDaColuna)
{
columnIndex = i;
// Display a message box
//MessageBox.Show(Convert.ToString(i));
break;
}
}
if (columnIndex != -1)
{
int ultimoValor = int.MinValue; // Valor inicial menor possível
// Percorra as linhas da GridView
foreach (GridViewRow row in GridView1.Rows)
{
// Encontre o TextBox dentro da célula da coluna
TextBox textBox = row.Cells[columnIndex].FindControl("Box2") as TextBox;
if (textBox != null && int.TryParse(textBox.Text, out int valorCelula))
{
if (valorCelula > ultimoValor)
{
ultimoValor = valorCelula;
}
}
}
if (ultimoValor != int.MinValue)
{
Console.WriteLine($"Último valor numérico: {ultimoValor}");
// Faça o que você precisa com o valor aqui
x_nid = ultimoValor + 1;
// Display a message box
//MessageBox.Show(Convert.ToString(x_nid));
}
else
{
Console.WriteLine("Não foram encontrados valores numéricos na coluna.");
}
}
else
{
Console.WriteLine("A coluna não foi encontrada na GridView.");
}
}
else
{
string connetionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****";
string query = "select isnull(max(nid),0) + 1 as nid from u_aprov where fref = '" + x_fref + "' ";
using (SqlConnection connection = new SqlConnection(connetionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
x_nid = Convert.ToInt32(reader["nid"]);
Console.WriteLine($"Último valor: {x_nid}");
}
else
{
Console.WriteLine("Não foram encontrados valores.");
}
}
}
}
}
int numeroInt = int.Parse(multiplicador);
DataTable dt;
if (ViewState["CurrentTable"] == null)
{
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("nid", typeof(int));
dt.Columns.Add("Tipo", typeof(string));
dt.Columns.Add("Diâmetro", typeof(int));
dt.Columns.Add("Espessura", typeof(int));
dt.Columns.Add("Qualidade", typeof(string));
dt.Columns.Add("Costura", typeof(string));
dt.Columns.Add("Medida", typeof(int));
dt.Columns.Add("Heat Number", typeof(string));
dt.Columns.Add("Obra", typeof(string));
dt.Columns.Add("Receção", typeof(string));
dt.Columns.Add("Observações", typeof(string));
ViewState["CurrentTable"] = dt;
}
else
{
dt = ViewState["CurrentTable"] as DataTable;
}
int z_nid = dt.Rows.Count;
int novoNid = z_nid + 1;
for (int i = 0; i < numeroInt; i++)
{
// Adicionar alguns dados de exemplo
DataRow dr = dt.NewRow();
//dt.Rows.Add("y" + x_nid, x_nid, x_tipo, x_pol, x_esp, x_qual, x_Cost, x_medida, x_heatn, x_fref, x_rec, "");
dr["ID"] = string.Empty;
dr["nid"] = 0;
dr["Tipo"] = string.Empty;
dr["Diâmetro"] = 0;
dr["Espessura"] = 0;
dr["Qualidade"] = string.Empty;
dr["Costura"] = string.Empty;
dr["Medida"] = 0;
dr["Heat Number"] = string.Empty;
dr["Obra"] = string.Empty;
dr["Receção"] = string.Empty;
dr["Observações"] = string.Empty;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
//ViewState["CurrentTable"] = dt;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
if (i >= z_nid)
{
string x_tipo = DropDownList1.SelectedValue;
string x_pol = DropDownList2.SelectedValue;
string x_esp = DropDownList3.SelectedValue;
string x_qual = DropDownList5.SelectedValue;
string x_medida = TextBox1.Text;
string x_heatn = TextBox2.Text;
//string x_fref = DropDownList4.SelectedValue;
string x_rec = TextBox3.Text;
((TextBox)row.FindControl("Box1")).Text = "y" + novoNid;
((TextBox)row.FindControl("Box2")).Text = Convert.ToString(novoNid);
((TextBox)row.FindControl("Box3")).Text = x_tipo;
((TextBox)row.FindControl("Box4")).Text = x_pol;
((TextBox)row.FindControl("Box5")).Text = x_esp;
((TextBox)row.FindControl("Box6")).Text = x_qual;
CheckBox chkUpdate = (CheckBox)CheckBox1.FindControl("CheckBox1");
if (chkUpdate.Checked)
{
((CheckBox)row.FindControl("Box7")).Checked = true;
}
else
{
((CheckBox)row.FindControl("Box7")).Checked = false;
}
((TextBox)row.FindControl("Box8")).Text = x_medida;
((TextBox)row.FindControl("Box9")).Text = x_heatn;
((TextBox)row.FindControl("Box10")).Text = x_fref;
((TextBox)row.FindControl("Box11")).Text = x_rec;
((TextBox)row.FindControl("Box12")).Text = "";
novoNid++;
}
}
//GridView1.DataSource = dt;
////GridView1.DataBind();
//ViewState["CurrentTable"] = dt;
//ViewState["valorArmazenado"] = va + novoNid; // Armazena o valor na primeira vez que o botão é clicado
ViewState["CurrentTable"] = dt;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
С помощью этого кода при втором щелчке мыши первоначально добавленные строки очищаются.
Подробнее здесь:
https://stackoverflow.com/questions/770 ... d-click-re
1730374633
Anonymous
Мне нужна помощь в реализации функции, позволяющей вводить данные в GridView с текстовыми полями через текстовые поля и DropDownLists. Впоследствии я стремлюсь применять операцию умножения каждый раз при нажатии определенной кнопки. Как только это умножение будет выполнено, я собираюсь отредактировать, если необходимо, представление сетки и выполнить еще одно событие нажатия кнопки, чтобы сохранить измененные данные. Это разметка .aspx:< /p> [code] [/code] Код, который я пробовал в файле кода программной части C#: [code]using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; using CheckBox = System.Web.UI.WebControls.CheckBox; using TextBox = System.Web.UI.WebControls.TextBox; namespace Lista_Tubos_e_Vigas { public partial class WebForm1 : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { string comentario = txtComentario1.Value; } protected void Button2_Click(object sender, EventArgs e) { string comentario = txtComentario2.Value; } protected void Button3_Click(object sender, EventArgs e) { string comentario = txtComentario3.Value; } protected void Button4_Click(object sender, EventArgs e) { string comentario = txtComentario4.Value; } protected void Gravar1_click(object sender, EventArgs e) { string connectionString; SqlConnection cnn; SqlCommand command; SqlDataReader dataReader; SqlDataAdapter adapter = new SqlDataAdapter(); String sql2, Output = " "; connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****"; cnn = new SqlConnection(connectionString); cnn.Open(); sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario1.InnerText + "', 'u_ltv1', '', getdate(), '', '', getdate(),''"; command = new SqlCommand(sql2, cnn); adapter.InsertCommand = new SqlCommand(sql2, cnn); dataReader = command.ExecuteReader(); while (dataReader.Read()) { Output = Output + dataReader.GetValue(0); } command.Dispose(); command.Dispose(); cnn.Close(); //command.ExecuteNonQuery(); string display = Output; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true); // Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx"); // ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true); // Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); // ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true); } protected void Gravar2_click(object sender, EventArgs e) { string connectionString; SqlConnection cnn; SqlCommand command; SqlDataReader dataReader; SqlDataAdapter adapter = new SqlDataAdapter(); String sql2, Output = " "; connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****"; cnn = new SqlConnection(connetionString); cnn.Open(); sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario2.InnerText + "', 'u_ltv2', '', getdate(), '', '', getdate(),''"; command = new SqlCommand(sql2, cnn); adapter.InsertCommand = new SqlCommand(sql2, cnn); dataReader = command.ExecuteReader(); while (dataReader.Read()) { Output = Output + dataReader.GetValue(0); } command.Dispose(); command.Dispose(); cnn.Close(); // command.ExecuteNonQuery(); string display = Output; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true); // Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx"); // ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true); // Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); // ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true); } protected void Gravar3_click(object sender, EventArgs e) { string connectionString; SqlConnection cnn; SqlCommand command; SqlDataReader dataReader; SqlDataAdapter adapter = new SqlDataAdapter(); String sql2, Output = " "; connectionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****"; cnn = new SqlConnection(connectionString); cnn.Open(); sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario3.InnerText + "', 'u_ltv3', '', getdate(), '', '', getdate(),''"; command = new SqlCommand(sql2, cnn); adapter.InsertCommand = new SqlCommand(sql2, cnn); dataReader = command.ExecuteReader(); while (dataReader.Read()) { Output = Output + dataReader.GetValue(0); } command.Dispose(); command.Dispose(); cnn.Close(); // command.ExecuteNonQuery(); string display = Output; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true); // Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx"); // ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true); // Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); // ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true); } protected void Gravar4_click(object sender, EventArgs e) { string connetionString; SqlConnection cnn; SqlCommand command; SqlDataReader dataReader; SqlDataAdapter adapter = new SqlDataAdapter(); String sql2, Output = " "; connetionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****"; cnn = new SqlConnection(connetionString); cnn.Open(); sql2 = "insert into dytable (dytablestamp, campo, entityname, ousrinis, ousrdata, ousrhora, usrinis, usrdata, usrhora) select left(newid(),25), '" + txtComentario4.InnerText + "', 'u_ltv4', '', getdate(), '', '', getdate(),''"; command = new SqlCommand(sql2, cnn); adapter.InsertCommand = new SqlCommand(sql2, cnn); dataReader = command.ExecuteReader(); while (dataReader.Read()) { Output = Output + dataReader.GetValue(0); } command.Dispose(); command.Dispose(); cnn.Close(); //command.ExecuteNonQuery(); string display = Output; ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Registado com sucesso');window.location.href='/WebForm1.aspx?';", true); //Response.Redirect("http://Lista_Tubos_e_Vigas.pipemasters.pt/WebForm1.aspx"); //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('checking');window.location.href='PHC.aspx';", true); //Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); //ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.close();", true); } protected void Button6_Click(object sender, EventArgs e) { //int va = (int)ViewState["valorArmazenado"]; //MessageBox.Show(Convert.ToString(va)); string multiplicador = TextBox4.Text; //string x_tipo = DropDownList1.SelectedValue; //string x_pol = DropDownList2.SelectedValue; //string x_esp = DropDownList3.SelectedValue; //string x_qual = DropDownList5.SelectedValue; //string x_medida = TextBox1.Text; //string x_heatn = TextBox2.Text; string x_fref = DropDownList4.SelectedValue; //string x_rec = TextBox3.Text; int x_nid = 0; if (GridView1.Rows.Count > 0) { string nomeDaColuna = "nid"; // Substitua pelo nome correto da coluna int columnIndex = -1; // Índice inicial inválido // Encontre o índice da coluna pelo nome do cabeçalho for (int i = 0; i < GridView1.Columns.Count; i++) { if (GridView1.Columns[i].HeaderText == nomeDaColuna) { columnIndex = i; // Display a message box //MessageBox.Show(Convert.ToString(i)); break; } } if (columnIndex != -1) { int ultimoValor = int.MinValue; // Valor inicial menor possível // Percorra as linhas da GridView foreach (GridViewRow row in GridView1.Rows) { // Encontre o TextBox dentro da célula da coluna TextBox textBox = row.Cells[columnIndex].FindControl("Box2") as TextBox; if (textBox != null && int.TryParse(textBox.Text, out int valorCelula)) { if (valorCelula > ultimoValor) { ultimoValor = valorCelula; } } } if (ultimoValor != int.MinValue) { Console.WriteLine($"Último valor numérico: {ultimoValor}"); // Faça o que você precisa com o valor aqui x_nid = ultimoValor + 1; // Display a message box //MessageBox.Show(Convert.ToString(x_nid)); } else { Console.WriteLine("Não foram encontrados valores numéricos na coluna."); } } else { Console.WriteLine("A coluna não foi encontrada na GridView."); } } else { string connetionString = @"Server=AGUA;Database=PIPEMASTERS ;Persist Security Info=True;User ID=sa;Password=*****"; string query = "select isnull(max(nid),0) + 1 as nid from u_aprov where fref = '" + x_fref + "' "; using (SqlConnection connection = new SqlConnection(connetionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(query, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { x_nid = Convert.ToInt32(reader["nid"]); Console.WriteLine($"Último valor: {x_nid}"); } else { Console.WriteLine("Não foram encontrados valores."); } } } } } int numeroInt = int.Parse(multiplicador); DataTable dt; if (ViewState["CurrentTable"] == null) { dt = new DataTable(); dt.Columns.Add("ID", typeof(string)); dt.Columns.Add("nid", typeof(int)); dt.Columns.Add("Tipo", typeof(string)); dt.Columns.Add("Diâmetro", typeof(int)); dt.Columns.Add("Espessura", typeof(int)); dt.Columns.Add("Qualidade", typeof(string)); dt.Columns.Add("Costura", typeof(string)); dt.Columns.Add("Medida", typeof(int)); dt.Columns.Add("Heat Number", typeof(string)); dt.Columns.Add("Obra", typeof(string)); dt.Columns.Add("Receção", typeof(string)); dt.Columns.Add("Observações", typeof(string)); ViewState["CurrentTable"] = dt; } else { dt = ViewState["CurrentTable"] as DataTable; } int z_nid = dt.Rows.Count; int novoNid = z_nid + 1; for (int i = 0; i < numeroInt; i++) { // Adicionar alguns dados de exemplo DataRow dr = dt.NewRow(); //dt.Rows.Add("y" + x_nid, x_nid, x_tipo, x_pol, x_esp, x_qual, x_Cost, x_medida, x_heatn, x_fref, x_rec, ""); dr["ID"] = string.Empty; dr["nid"] = 0; dr["Tipo"] = string.Empty; dr["Diâmetro"] = 0; dr["Espessura"] = 0; dr["Qualidade"] = string.Empty; dr["Costura"] = string.Empty; dr["Medida"] = 0; dr["Heat Number"] = string.Empty; dr["Obra"] = string.Empty; dr["Receção"] = string.Empty; dr["Observações"] = string.Empty; dt.Rows.Add(dr); } GridView1.DataSource = dt; GridView1.DataBind(); //ViewState["CurrentTable"] = dt; for (int i = 0; i < GridView1.Rows.Count; i++) { GridViewRow row = GridView1.Rows[i]; if (i >= z_nid) { string x_tipo = DropDownList1.SelectedValue; string x_pol = DropDownList2.SelectedValue; string x_esp = DropDownList3.SelectedValue; string x_qual = DropDownList5.SelectedValue; string x_medida = TextBox1.Text; string x_heatn = TextBox2.Text; //string x_fref = DropDownList4.SelectedValue; string x_rec = TextBox3.Text; ((TextBox)row.FindControl("Box1")).Text = "y" + novoNid; ((TextBox)row.FindControl("Box2")).Text = Convert.ToString(novoNid); ((TextBox)row.FindControl("Box3")).Text = x_tipo; ((TextBox)row.FindControl("Box4")).Text = x_pol; ((TextBox)row.FindControl("Box5")).Text = x_esp; ((TextBox)row.FindControl("Box6")).Text = x_qual; CheckBox chkUpdate = (CheckBox)CheckBox1.FindControl("CheckBox1"); if (chkUpdate.Checked) { ((CheckBox)row.FindControl("Box7")).Checked = true; } else { ((CheckBox)row.FindControl("Box7")).Checked = false; } ((TextBox)row.FindControl("Box8")).Text = x_medida; ((TextBox)row.FindControl("Box9")).Text = x_heatn; ((TextBox)row.FindControl("Box10")).Text = x_fref; ((TextBox)row.FindControl("Box11")).Text = x_rec; ((TextBox)row.FindControl("Box12")).Text = ""; novoNid++; } } //GridView1.DataSource = dt; ////GridView1.DataBind(); //ViewState["CurrentTable"] = dt; //ViewState["valorArmazenado"] = va + novoNid; // Armazena o valor na primeira vez que o botão é clicado ViewState["CurrentTable"] = dt; } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } } } [/code] С помощью этого кода при втором щелчке мыши первоначально добавленные строки очищаются. Подробнее здесь: [url]https://stackoverflow.com/questions/77010263/asp-net-c-add-to-gridview-with-textbox-programmatically-but-in-second-click-re[/url]