Fill a grid view by a drop down list - asp.net

I have a drop down list ; a sqldatasource and a gridview .
I want to fill the grid view by the choice in the drop down list.
How can i implement this fill ?
Thanks
My question is not a duplicate of this Click
because it want to populate a drop down list inside the grid view instead my question is : by a choice of a drop down list , fill a grid view.
EDIT (Because i am in negative rep.) :
What i have tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}

aspx page
<asp:DropDownList runat="server" ID="drp" AutoPostBack="true" OnSelectedIndexChanged="drp_SelectedIndexChanged"></asp:DropDownList>
<asp:GridView runat="server" ID="grd" AutoGenerateColumns="true"></asp:GridView>
code behind of aspx
protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
grd = dataSource;
grd.DataBind();
}
Bind grid on selection index change event of dropdown.

Related

how to bind gridview to sqldatasource to our own created form

I have a form and 'Add' button. when i click on add then i insert data into database and also i have sqldatasource in which i specify only select,update,delete commands. when i insert data on Add button then i want to refresh and fill the grid automatically.
my sqldatasource id is "sqldatasourceDenter" and i have specified it in my gridview datasourceID="sqldatasourceDenter".
i have tried this
GridView1.DataSourceID = sqldatasourceDenter;
it gives me the error cannot convert sqldatasource to string
i have also defined datasource but it tells both me both datasource, datasourceID cannot be defined.
I actually want to insert data on my 'Add' button then refresh the sqldataSourceDenter to fill the grid.
This is my add button click event function:
..... add_Click(object sender, EventArgs e){
..
.... /* here i have other code*/
.....
else {
string dentername = dname.Text.ToString();
string denteraddress = daddress.Text.ToString();
string dentercontact = dcontact.Text.ToString();
//create sql inset query and take to insert query ftn for execution
string dquery = string.Format("INSERT INTO Denters(D_NIC, D_Name, D_Address, D_Contact) VALUES('{0}','{1}','{2}','{3}')", denternic, dentername, denteraddress, dentercontact);
InsertIntoDB.InsertQuery(dquery);
if (InsertIntoDB.count > 0)
{
gvDenter.DataSourceID = SqlDataSourceDenter;
Response.Write("<script>alert('Denter added successfully')</script>");
InsertIntoDB.count = 0;
ClearDenterFields();
}
}
}
My aspx code is:
<asp:SqlDataSource ID="SqlDataSourceDenter" runat="server" ConnectionString="<%$ ConnectionStrings:VehiclesSystemConnectionString2 %>"
SelectCommand="SELECT [D_NIC], [D_Name], [D_Address], [D_Contact] FROM [Denters]">
</asp:SqlDataSource>
<asp:GridView ID="gvDenter" Visible="False" DataKeyNames="D_NIC" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceDenter" >
</asp:GridView>
You can have something like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataToGrid();
}
}
protected void BindDataToGrid()
{
string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
string myQuery = "SELECT * FROM MYTABLE";
SqlCommand cmd = new SqlCommand(myQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Add(object sender, EventArgs e)
{
//Insert To DB Code here
}

How to add TemplateField to a gridview in the code behind?

I have a DropDownList which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.
Following is my bind method. I have two problems:
I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?
My bind method
private void BindGridView()
{
DataSet ds = new DataSet();
try
{
ds = …
if (ds.Tables.Count > 0)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
TemplateField tField = new TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(tField);
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
else
{
…
}
}
catch (Exception ex)
{
…
}
}
There are various steps that should be taken care of:
STEP I::
Create a class inheriting the ITemplate interface. Override the method InstantiateIn() of the ITemplate interface.
STEP II:
Define a constructor for your class that takes a ListItemType object as its parameter.
STEP III::
If the Control being added to the container's ControlCollection has to be bound to some DataSource Column, then register the
handler for the OnDataBinding event. When the event occurs, retrieve the text from the data source and assign it to your control. For Example, hyprLnk_DataBinding event is defined for Binding Data to your controls created inside ItemTemplate.
public class TemplateGenerator : ITemplate // Class inheriting ITemplate
{
ListItemType type;
string columnName;
public TemplateGenerator(ListItemType t, string cN)
{
type = t;
columnName= cN;
}
// Override InstantiateIn() method
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (type)
{
case ListItemType.Item:
HyperLink hyprLnk = new HyperLink();
hyprLnk.Target = "_blank"; //Optional.
hyprLnk.DataBinding+=new EventHandler(hyprLnk_DataBinding);
container.Controls.Add(hyprLnk);
break;
}
}
// The DataBinding event of your controls
void hyprLnk_DataBinding(object sender, EventArgs e)
{
HyperLink hyprlnk = (HyperLink)sender;
GridViewRow container = (GridViewRow)hyprlnk.NamingContainer;
object bindValue = DataBinder.Eval(container.DataItem,columnName);
// Adding check in case Column allows null values
if (bindValue != DBNull.Value)
{
hyprlnk.Text = bindValue.ToString();
hyprlnk.NavigateUrl = "http://www.google.com";
}
}
}
That's all. Above was just a sample to create ItemTemplate dynamically for GridView and add controls to the Item Template.
Now, Below is the function that will actually carry out the calls to create Template Columns dynamically. You can call this function when required for e.g. from your DropDownList event Handler.
protected void GenerateGridViewColumnsDynamically()
{
// Create the TemplateField
TemplateField firstName = new TemplateField();
firstName.HeaderText = "First_Name";
firstName.ItemTemplate = new TemplateGenerator(ListItemType.Item, "FirstName");
// Showing boundField example just for more context
BoundField lastName = new BoundField();
lastName.DataField = "LastName";
lastName.HeaderText = "Last_Name";
// Add the Columns now
MyGridView.Columns.Add(firstName);
MyGridView.Columns.Add(lastName);
}
NOTE:: FirstName and LastName are the Columns whose Names are passed to the constructor of your custom class: TemplateGenerator.
I have done the same functionality as below with custom paging(using storedProc) for 100+ million records in many tables, update, delete and insert also:
CREATE PROCEDURE [dbo].[sp_Mk]
#PageIndex INT,
#PageSize INT,
#tableName nvarchar(255),
#totalRow INT Output
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
Declare #anotherSql NVARCHAR(1000)
DECLARE #ParamDefinition NVARCHAR(500)
--DECLARE #totalRow INT
Set #sql = 'WITH TempResult AS( SELECT * FROM '+#tableName+'), TempCount AS ( SELECT COUNT(*) AS MaxRows FROM TempResult )
SELECT * FROM TempResult, TempCount ORDER BY (Select Null)
OFFSET '+CONVERT(VARCHAR(20),(#PageIndex-1)*#PageSize) +' ROWS FETCH NEXT '+CONVERT(VARCHAR(20),#PageSize)+' ROWS ONLY'
PRINT #SQL
EXECUTE sp_executesql #SQL
Set #anotherSql=N'SELECT COUNT(*) as totalRow FROM '+#tableName
SET #ParamDefinition = N'#totalRowOutPut INT OUTPUT'
--PRINT #anotherSql
Execute sp_executesql #anotherSql,
#ParamDefinition,
--#tableNameInput=#tableName,
#totalRowOutPut=#totalRow OUTPUT
End
<asp:GridView CssClass="table-striped header-fixed" ID="grdDynamic" runat="server" AutoGenerateColumns="True" ShowHeaderWhenEmpty="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
OnRowEditing="OnRowEditing_grdDynamic" OnRowUpdating="OnRowUpdating_grdDynamic" OnRowCancelingEdit="OnRowCancelingEdit_grdDynamic" OnRowDeleting="OnRowDeleting_grdDynamic" OnRowDataBound="OnRowDataBound_grdDynamic">
</asp:GridView><br/>
<asp:linkbutton id="AddButton" runat="server" commandname="Add" text="Insert: " OnClick="AddNewButton_Click" /><br/>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" CssClass="pagination-ys" runat="server" Text = '<%#Eval("Text") %>' CommandArgument = '<%# Eval("Value") %>' Enabled = '<%# Eval("Enabled") %>' OnClick = "Page_Changed"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater><asp:HiddenField runat="server" id="hdnPageIndex" Value="1"></asp:HiddenField>
SqlConnectionStringBuilder builder;
int pageSize = 100;
protected void Page_Load(object sender, EventArgs e)
{
builder = new SqlConnectionStringBuilder(connectionString);
if (!IsPostBack)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
connObj.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='" + builder.InitialCatalog + "' AND TABLE_NAME Not In('AspNetUsers') Order By TABLE_NAME", connObj))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
ddlTableNames.DataSource = ds;
ddlTableNames.DataBind();
ddlTableNames.Items.Insert(0, new ListItem("Select Table", String.Empty));
}
}
}
//}
//else if(ddlTableNames.Visible) ddlTableNames.Visible = false;
}
protected void ddlTableNames_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlTableNames.SelectedValue != "")
{
grdDynamic.Visible = true;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
else if (grdDynamic.Visible == true) grdDynamic.Visible = false;
}
private void BindGrid(string selectedTable, int pageIndex, bool addNewRow=false)
{
using (SqlConnection connObj = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_Mk", connObj))
{
int recordCount=0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", pageSize);
cmd.Parameters.AddWithValue("#tableName", ddlTableNames.SelectedValue);
SqlParameter totalRow = new SqlParameter("#totalRow", SqlDbType.Int, 4);
totalRow.Direction = ParameterDirection.Output;
cmd.Parameters.Add(totalRow);
connObj.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
grdDynamic.DataSource = ds.Tables[0];
if (addNewRow) ds.Tables[0].Rows.Add();
recordCount = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);
grdDynamic.DataBind();
connObj.Close();
if (totalRow.Value != DBNull.Value)
{
}
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / pageSize);
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
pages.Add(new ListItem("First", "1", currentPage > 1));
for (int i = 1; i <= pageCount; i++)
{
ListItem item=new ListItem(i.ToString(), i.ToString(), i != currentPage);
if (i == currentPage) item.Attributes.Add("style", "color:red;");
pages.Add(item);
}
pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
hdnPageIndex.Value = pageIndex.ToString();
this.BindGrid(ddlTableNames.SelectedValue, pageIndex);
}
protected void OnRowEditing_grdDynamic(object sender, GridViewEditEventArgs e)
{
grdDynamic.EditIndex = e.NewEditIndex;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowUpdating_grdDynamic(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = grdDynamic.Rows[e.RowIndex];
string updateStatement = string.Empty;
for (int x = 0; x < row.Cells.Count; x++) updateStatement = updateStatement + grdDynamic.DataKeys[e.RowIndex].Values[x] + " = " + grdDynamic.DataKeys[e.RowIndex].Values[x] + ", ";
//int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
//using (SqlCommand cmd = new SqlCommand("UPDATE "+selectedTable"+ SET Name = #Name, Country = #Country WHERE CustomerId = #CustomerId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowCancelingEdit_grdDynamic(object sender, EventArgs e)
{
grdDynamic.EditIndex = -1;
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void OnRowDeleting_grdDynamic(object sender, GridViewDeleteEventArgs e)
{
int recordId = Convert.ToInt32(grdDynamic.DataKeys[e.RowIndex].Values[0]);
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM " + ddlTableNames.SelectedValue + " WHERE RecordId = #recordId"))
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value));
}
protected void btnGo_Click(object sender, EventArgs e)
{ int myInt;
if(txtPageSize.Text!=null && txtPageSize.Text !=string.Empty)
if(int.TryParse(txtPageSize.Text, out myInt)) pageSize = myInt;
hdnPageIndex.Value = "1";
this.BindGrid(ddlTableNames.SelectedValue, 1);
}
protected void AddNewButton_Click(object sender, EventArgs e)
{
hdnPageIndex.Value="1";
this.BindGrid(ddlTableNames.SelectedValue, Convert.ToInt32(hdnPageIndex.Value), true);
}
protected void OnRowDataBound_grdDynamic(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grdDynamic.EditIndex)
{
(e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
Hope it helps:

Paging in Gridview not working 2nd page data not showing data?

my gridview
<div style="margin-left: 280px">
<asp:GridView ID="exportGrdVw" runat="server" BackColor="White"
AllowPaging="True" PageSize="3"
OnPageIndexChanging="exportGrdVw_PageIndexChanging"
onpageindexchanged="exportGrdVw_PageIndexChanged">
</asp:GridView>
</div>
my code
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
BindEmployee();
}
}
public void BindEmployee()
{
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
the problem is gridview is displaying but when i click page 2. 2nd page data is not showing (blank). pls help me to solve this problem.
see that the code is correct or not
Use like below
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployee();
}
}
public void BindEmployee()
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
Your datatable gets initialize in every page load so you need to get the datatable
everytime before binding it to grid.
Set your page Index before binding it to grid
So your code should be like this
public void BindEmployee(int newPageIndex = -1)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.PageIndex = newPageIndex;
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
No need to call database on exportGrdVw_PageIndexChanging. Just declare DataTable table as static
You can try this:
GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Emp_Data ORDER BY [ID] DESC", con);
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);
GridView1.DataSource = DT1;
GridView1.DataBind();

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working

I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataBind();
}
I don't know how to bind the gridview in paging event, since I do not have any separate binding function.
there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BusinessKPIGrid.PageIndex = e.NewPageIndex;
bindyourgrid();
}
try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
ViewState["ds"]=ds;
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
BusinessKPIGrid.DataBind();
}
From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvworker.PageIndex = e.NewPageIndex;
//result got from ddl list i.e bind your data set
}

Resources