Filtrar Informaçãoe a partir Dropdown
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
//Ao inicializar a pagina, seleciona todos os lotes da tabela e lista no grid
//São selecionados apenas os campos necessários para ver no grid. Select SQL
dsLotes.SelectCommand = "SELECT ID_Lote, numero_protocolo, Data, DataHora_Recebimento, Percentual, ID_Terapeuta From dbo.Lotes";
//Esta é a chave primária, ou seja, o ID único de registros da tabela de lotes
string[] KeyNames = new string[1];
KeyNames[0] = "ID_LOTE";
//Dizendo ao grid quem (campo) que será a chave primária
grdLotes.DataKeyNames = KeyNames;
//Definindo o dataset de Lotes que contem o comando select acima para o Grid.
grdLotes.DataSourceID = "dsLotes";
}
}
protected void btnFiltrar_Click(object sender, EventArgs e)
{
//Redefinindo o comando SELECT do dataset dsLotes contendo os parâmetros passados no formulário (filtro).
// Neste SELECT estou convertendo as datas de parametro para o formato DATE pois estão vindo como String.
dsLotes.SelectCommand = "SELECT ID_Lote, numero_protocolo, Data, DataHora_Recebimento, Percentual, ID_Terapeuta, (SELECT SUM(TotalGeralGuia) AS Total FROM AtendimentosNovo WHERE (ID_Lote = L.ID_Lote)) AS Total FROM Lotes AS L WHERE (ID_Convenio = @id_convenio) AND (ID_Lote = @id_lote) AND (ID_Status = @id_status) AND (ID_Terapeuta = @id_terapeuta) AND (paciente=@paciente) AND (CONVERT(VARCHAR(10),DataHora_Recebimento, 1) BETWEEN CONVERT(VARCHAR(10), @dt1, 1) AND CONVERT(VARCHAR(10), @dt2, 1)) ORDER BY Data DESC, DataHora_Recebimento DESC";
//Limpando parametros do Dataset, pois se rodar o filtro novamente na mesma página, estes parametros não poderão ser criados novamente
//senão ficam repetidos e ocorre erro.
dsLotes.SelectParameters.Clear();
//Adicionando os parametros para o Dataset dsLotes. O nome de cada parametro destes, deve ser igual aos parametros do SELECT acima,
//só que sem o arroba @ na frente. Para cada parametro do SELECT é associado o valor do controle do formulário, assim,
//o SELECT filtra de acordo com dados digitados pelo usuário.
//Se houver necessidade de retirar algum parametro deste filtro/select, excluir uma linha dessas correspondente
//ao parametro a ser excluido e depois remover o filtro deste parametro do SELECT de filtro acima.
dsLotes.SelectParameters.Add("id_convenio", drpConvenio.SelectedValue);
dsLotes.SelectParameters.Add("id_lote", txtID_Lote.Text);
dsLotes.SelectParameters.Add("id_status", drpStatus.SelectedValue);
dsLotes.SelectParameters.Add("id_terapeuta", drpMedicos.SelectedValue);
dsLotes.SelectParameters.Add("paciente", txtPaciente.Text);
dsLotes.SelectParameters.Add("dt1", Convert.ToString(txtPeriodoDe.Text));
dsLotes.SelectParameters.Add("dt2", Convert.ToString(txtPeriodoAte.Text));
//Agora que definimos o Select de filtro do Dataset dsLotes e seus parametros, podemos associá-lo ao Grid.
grdLotes.DataSourceID = "dsLotes";
}
protected void grdLotes_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Quando clico em EDIT numa linha do grid, permite editar o protocolo do grid.
// Quando termindo de editar, e clico ATUALIZAR, entra nesta rotina, define o comando de update
// a ser executado no banco onde será atualizado o numero de protocolo para o lote atual.
dsLotes.UpdateCommand = "UPDATE dbo.Lotes SET numero_protocolo = @Num_Protocolo WHERE ID_Lote=@Id_Lote";
dsLotes.UpdateParameters.Add("Id_Lote", txtID_Lote.Text);
//Aqui, estou definindo o valor do protocolo a ser atualizado.
// grdLotes.Rows[e.RowIndex].Cells[2].Text é o valor do protocolo da linha e coluna atual do Grid que está sendo editado.
dsLotes.UpdateParameters.Add("Num_Protocolo", grdLotes.Rows[e.RowIndex].Cells[2].Text);
}
}
Olá Pessoal Hoje vou postar um exemplo bem simples usando Aspx/C#.
Vamos lá..
Estou usando Master Page nessa pagina, mas o objetivo desse post é mostrar um pouco dessa aplicação simples, no proximo artigo vou mostrar um exemplo Simples "Tambem" de Master Pages. Vamos lá!
<%@ Page Language="C#" MasterPageFile="~/Principal.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EditandoDadosGridView.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<title>Pesquisa Cadastro</title>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<span class="style1">Cadastro Cliente</span><br />
<div>
<div>
<table class="Celula"><tr><td style="padding:1px;">
<br />Nome:
<asp:TextBox ID="txtNome" runat="server" Height="22px" Width="128px" ></asp:TextBox>
<br /></td></tr></table>
<table class="Celula"><tr><td style="padding:1px;" >
<br /> Cpf:
<asp:TextBox ID="txtCPF" runat="server" Height="22px" ></asp:TextBox>
<br /></td></table>
<table class="Celula"><td style="padding:1px;" class="style2">
RG:
<asp:TextBox ID="txtRG" runat="server" Height="22px"></asp:TextBox>
</td></table>
Ativo<br />
</div>
<asp:RadioButtonList ID="RadioButtonListAtivo" runat="server"
style="margin-right: 0px" Width="63px">
<asp:ListItem Value="Sim" Text="Sim" ></asp:ListItem>
<asp:ListItem Value="Não" Text="Não" ></asp:ListItem>
</asp:RadioButtonList>
<br />
</div>
<asp:GridView ID="grdDados" runat="server" CellPadding="3" AutoGenerateColumns="False"
OnRowCommand="grdDados_RowCommand"
onrowcreated="grdDados_RowCreated"
AlternatingRowStyle-CssClass="alt" PageSize="5"
AllowSorting="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" onrowdatabound="grdDados_RowDataBound" ShowFooter="True"
AllowPaging="True" GridLines="Horizontal"
onpageindexchanged="grdDados_PageIndexChanged" PageIndex="5"
onpageindexchanging="grdDados_PageIndexChanging">
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
<asp:BoundField DataField="Nome" HeaderText="Nome" />
<asp:BoundField DataField="CPF" HeaderText="CPF" />
<asp:BoundField DataField="RG" HeaderText="RG" />
<asp:BoundField DataField="Ativo" HeaderText="Ativo" />
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>
<div>
<br />
<asp:Button ID="btnSalvar" runat="server" Text="Salvar" onclick="btnSalvar_Click" />
<asp:Button ID="btnLimpar" runat="server" Text="Limpar"
onclick="btnLimpar_Click1" />
<br />
</div>
<br />
<br />
</div>
</asp:Content>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace EditandoDadosGridView
{
public partial class WebForm1 : System.Web.UI.Page
{
string strSelect = "Select Nome, CPF, RG from Documentos";
string strInsert = "insert into Documentos (Nome, CPF, RG, Ativo)values(@Nome, @CPF, @RG, @Ativo)";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<dados> lstRetorno = CarregarGridView();
if (lstRetorno != null && lstRetorno.Count > 0)
{
grdDados.DataSource = lstRetorno;
grdDados.DataBind();
this.grdDados.Rows[0].Style.Add("background-color", "D8D8D8");
}
}
}
public class dados
{
public string Nome { get; set; }
public string CPF { get; set; }
public string RG { get; set; }
public string Ativo { get; set; }
}
private void valida()
{
if (txtNome.Text.Length < 1)
{
Response.Write("<script>alert('Favor Preencher Campo!'); window.location.href='WebForm1.aspx';</script>");
}
}
public void Salvar()
{
SqlConnection strConnectioString = new SqlConnection(new System.Configuration.AppSettingsReader().GetValue("ConexaoBD", System.Type.GetType("System.String")).ToString());
using (SqlCommand objCommand = new SqlCommand(strInsert, strConnectioString))
{
strConnectioString.Open();
try
{
objCommand.Parameters.AddWithValue("Nome", txtNome.Text);
objCommand.Parameters.AddWithValue("CPF", txtCPF.Text);
objCommand.Parameters.AddWithValue("RG", txtRG.Text);
objCommand.Parameters.AddWithValue("Ativo", RadioButtonListAtivo.SelectedValue);
objCommand.ExecuteNonQuery();
CarregaDados();
}
catch (Exception Erro)
{
throw new Exception(Erro.Message);
}
finally
{
strConnectioString.Close();
}
}
}
private List<dados> CarregarGridView()
{
List<dados> lstRetorno = new List<dados>();
SqlConnection strConnectionString = new SqlConnection(new System.Configuration.AppSettingsReader().GetValue("ConexaoBD", System.Type.GetType("System.String")).ToString());
string strInstrucaoSelect = "Select Nome, CPF, RG, Ativo from Documentos";
using (strConnectionString)
{
using (SqlCommand objCommand = new SqlCommand(strInstrucaoSelect, strConnectionString))
{
try
{
strConnectionString.Open();
SqlDataReader objDataReader = objCommand.ExecuteReader();
if (objDataReader.HasRows)
{
while (objDataReader.Read())
{
dados objDados = new dados();
objDados.Nome = objDataReader["Nome"].ToString();
objDados.CPF = objDataReader["CPF"].ToString();
objDados.RG = objDataReader["RG"].ToString();
objDados.Ativo = objDataReader["Ativo"].ToString();
lstRetorno.Add(objDados);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
strConnectionString.Close();
}
}
}
return lstRetorno;
}
public List<dados> CarregaDados()
{
List<dados> lstRetorno = new List<dados>();
SqlConnection strConnectioString = new SqlConnection(new System.Configuration.AppSettingsReader().GetValue("ConexaoBD", System.Type.GetType("System.String")).ToString());
using (SqlCommand objCommand = new SqlCommand(strSelect, strConnectioString))
{
try
{
strConnectioString.Open();
SqlDataReader objDataReader = objCommand.ExecuteReader();
if (objDataReader.HasRows)
{
while (objDataReader.Read())
{
dados objDados = new dados();
objDados.Nome = objDataReader["Nome"].ToString();
objDados.CPF = objDataReader["CPF"].ToString();
objDados.RG = objDataReader["RG"].ToString();
objDados.Ativo = objDataReader["Ativo"].ToString();
lstRetorno.Add(objDados);
}
}
}
catch (Exception Erro)
{
throw new Exception(Erro.Message);
}
finally
{
strConnectioString.Close();
}
return lstRetorno;
}
}
protected void btnSalvar_Click(object sender, EventArgs e)
{
Salvar();
CarregaDados();
{
Response.Write("<script>alert('Registro Gravado!'); window.location.href='WebForm1.aspx';</script>");
}
}
protected void grdDados_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void grdDados_RowCreated(object sender, GridViewRowEventArgs e)
{
}
protected void grdDados_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
private void limpar()
{
txtNome.Text = "";
txtRG.Text = "";
txtCPF.Text= "";
}
protected void btnLimpar_Click1(object sender, EventArgs e)
{
limpar();
}
protected void grdDados_PageIndexChanged(object sender, EventArgs e)
{
}
protected void grdDados_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
}
}
}