Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycaroafonso/29d91136c7facd38dbbbf3f975b84e74 to your computer and use it in GitHub Desktop.
Save ycaroafonso/29d91136c7facd38dbbbf3f975b84e74 to your computer and use it in GitHub Desktop.
GridView paginada com checkbox em C# webform
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
///
/// Armazena as ID's em uma viewstate
///
public List lstIdChkChecados
{
get
{
if (ViewState["lstIdChkChecados"] == null)
{
ViewState["lstIdChkChecados"] = new List();
}
return (List)ViewState["lstIdChkChecados"];
}
set
{
ViewState["lstIdChkChecados"] = value;
}
}
///
/// atualiza o viewstate com as ID's da DataKey (DataKeyNames) da gridview.
///
protected void AtualizaViewStateChkChecados()
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox Chk = ((CheckBox)row.FindControl("CheckBox1"));
if (Chk.Checked)
{
if (!lstIdChkChecados.Contains((int)GridView1.DataKeys[row.RowIndex][0]))
{
lstIdChkChecados.Add((int)GridView1.DataKeys[row.RowIndex][0]);
}
}
else
{
if (lstIdChkChecados.Contains((int)GridView1.DataKeys[row.RowIndex][0]))
{
lstIdChkChecados.Remove((int)GridView1.DataKeys[row.RowIndex][0]);
}
}
}
}
///
/// Quando clica para mudar de página, é executado o método AtualizaViewStateChkChecados() antes de atualizar o GridView.
///
///
///
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
AtualizaViewStateChkChecados();
}
///
/// Depois que ocorre a mudança, verifica se na página atual da GridView existe checkbox marcados.
///
///
///
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
foreach (DataRowView row in SqlDataSource1.Select(DataSourceSelectArguments.Empty))
{
if ((bool)row["Ativo"])
{
lstIdChkChecados.Add((int)row["ID"]);
}
}
}
foreach (GridViewRow row in GridView1.Rows)
{
((CheckBox)row.FindControl("CheckBox1")).Checked = lstIdChkChecados.Contains((int)GridView1.DataKeys[row.RowIndex][0]);
}
}
///
/// Atualiza a tabela do banco de dados usando lstIdChkChecados
///
///
///
protected void btnAtualizar_Click(object sender, EventArgs e)
{
AtualizaViewStateChkChecados();
SqlConnection conexao = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionStringSqlServer"].ConnectionString);
try
{
conexao.Open();
SqlCommand comando = new SqlCommand();
comando.Parameters.Add("@Ativo", SqlDbType.Bit).Value = false;
comando.CommandText = "UPDATE DotNet_GridViewPaginadaComCheckbox SET Ativo = @Ativo";
comando.CommandType = CommandType.Text;
comando.Connection = conexao;
comando.ExecuteNonQuery();
// Antes de fechar a conexão, passa por todos os itens do lstIdChkChecados e atualiza no banco, passando o campo Ativo para true.
comando.CommandText = "UPDATE DotNet_GridViewPaginadaComCheckbox SET Ativo = @Ativo WHERE ID = @ID";
comando.Parameters[0].Value = true;
comando.Parameters.Add("@ID", SqlDbType.Int);
foreach (int item in lstIdChkChecados)
{
comando.Parameters[1].Value = item;
comando.ExecuteNonQuery();
}
}
catch (Exception ex)
{
}
finally
{
conexao.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment