ASP.NET C# GridView paging options - c#

I am currently attempting to make gridview load 1 question at a time, when I set the paging to 1 it gives me this error.
Also using the VS15 SQL server

Try using an SqlAdapter instead of SqlDataReader. The reason is because you cannot Page back if you use SqlDataReader. SqlAdapter supports bidirectional traversal.
You were not using a Data table to retrieve the results form the select query. Use this instead
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
loadgrid();
}
}
private void loadgrid() {
con.Open();
cmd.CommandText = "SELECT TOP 4 * FROM [Question] ORDER BY NEWID()";
cmd.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.AllowPaging = true;
GridView1.DataBind();
}

Related

GridView not appearing on webpage

I am building a web form. I have one search field and a search button. I am connecting to MS Access database to retrieve and display the result on the grid view. But my grid view is not appearing on the web page.
Can anyone please help me to find out where I am wrong?
Here is my aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Smita\\Desktop\\Project.accdb");
DataTable dt = new DataTable() ;
if (txtMerchant.Text.Length > 0)
{
con.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand("select * from Test where Merchant ID like '" + txtMerchant.Text + "%'", con);
DBAdapter.Fill(dt);
GridView1.DataSource = dt;
}
You have to call the DataBind, binding method first after you assign the data source.
Like that:
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataSource = dt; //Assigned a blank table.
"dt" Doesn't seem to point to anything.

c# asp.net Index was out of range. when I trying to select a row

I have a gridview on my page. And I have 2 snippets of SQL code to binds that gridview.
First one is run on page load. If there are records returned from the first SQL, I can select a row on gridview.
But the problem is when there is no record returned from the first SQL, I have button that runs another SQL and binds its result to the gridview too. But when I try to select a row, I get this error:
Index was out of range. when I trying to select a row Must be non-negative and less than the size of the collection. Parameter name: index
My code is like that
First SQL (its run on page load)
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and thats the second SQL that when runs when I click button
void listelehepsi()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and this is the GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int secili;
secili = GridView1.SelectedIndex;
GridViewRow row = GridView1.Rows[secili]; // I GOT ERROR HERE
TextBox1.Text = row.Cells[1].Text;
}
why Am I getting this error ?
EDIT--
I got solve changing the page load sql like this;
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
if (!IsPostBack)
{
GridView1.DataBind();
}
else
{
//
}
baglanti.Close();
}
Make sure that you are not rebinding your datagrid on postback - you can do this in your PageLoad event - something like
if (!IsPostback)
{
... bind your datagrid
}
In the GridView1_SelectedIndexChanged event, could you simply do a RowCount to see if the value is != 0 before the other code runs?
if (GridView1.RowCount <= 0)
{
return;
}

call function with parameters in the Page Load .NET

I'm doing a filter form by 3 criteria, I'm having problems on the pagination since I do not load the data from the second page of the GridView, apparently I have to call my function that fills the GridView in the Load page event, but this function receives parameters that are the ones that the user enters in the search filter, How can I then call the function sending the parameters to that function in the page load event every time the page is changed in the GridView?
function
public DataTable AdvertSearch(string tittle, DateTime datel, DateTime date2)
{
SqlConnection con = new SqlConnection(Util.GetConnectionString("ConnectionString"));
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select*from table where titAdvert=#tittle or dateStart=#dateS" or dateEnd=#dateE;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#tittle", tittle== "" ? (object)DBNull.Value : tittle);
cmd.Parameters.AddWithValue("#dateS", date1== "" ? (object)DBNull.Value : date1);
cmd.Parameters.AddWithValue("#dateE", date2== "" ? (object)DBNull.Value : date2);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
search button
protected void BtnSearch_Click(object sender, EventArgs e)
{
GridView1.DataSource = AdvertSearch(txtTitle.Text,txtDateI.Text,txtDateF.Text);
GridView1.DataBind();
}
You need to specify a pageIndexChanging event to trigger the grid to be reloaded when the user clicks to the next page. Check out the code below:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = AdvertSearch(txtTitle.Text,txtDateI.Text,txtDateF.Text);
GridView1.DataBind();
}
And please write your code in english, as it makes it more readable for all programmers.

Refreshing multiple datagridviews with single button click

Not sure if this question has been asked before, so here goes..
I have a front end app coded in C# windows forms. On a second form i have two datagridviews that gets populated from two different sql server pre-defined views
I need to refresh both datagrids at the same time with a single button click
My button click even looks like this..
private void RefreshBTN_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
How i understand this is, C# opens new connection, queries the DB and returns by filling datagridview1 with the required data. I would like the same click event to request data from another sql view and populate another datagridview at the same time. Visually both grids are aligned vertically on the same form, one on to of the other.
Many thanks in advance
Move the code for refreshing Grid1 into a separate function. Then copy paste and duplicate that function for Grid2. Change the SQL for Grid2 as well as the Grid2 name. Rename the copied function with 2. Then add a call to both functions so your button click will refresh both grids.
private void RefreshBTN_Click(object sender, EventArgs e)
{
//call both functions to refresh both on button click
RefreshGrid1();
RefreshGrid2();
}
private void RefreshGrid1()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//give this function a unique name to represent the second grid refresh
private void RefreshGrid2()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//rename this to your second grid name
dataGridView2.DataSource = dt;
}

Gridview with DDl selected value

I had gridview which in load it will get data from database .And I added option for user to filter this grid view by DDl I did my code and the grid get data when load but when I selected DDl it didnot get any data and I made break point I noticed that Gridview1.Databind() hadnot any action on grid.So please any one help me
protected void Page_Load(object sender, EventArgs e)
{
DataTable DT = new DataTable();
if (DDlCity.SelectedIndex<0)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#DEALERAREA_ID", DDlCity.SelectedValue));
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
i suppose you got confused on what i said...no worries
here is a working example of you give example code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridFunction();
}
}
private void BindGridFunction()
{
try
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
if(DDlCity.SelectedIndex <0)
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
}
else
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#DEALERAREA_ID", DDlCity.SelectedItem.Value));
}
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
catch(Exception ex)
{
DT = null; // etc...etc.. clear objects created
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridFunction();
}
I hope you get what i was trying to say. You can change the code according to you need.
Not tested yet but m sure will work.
Note : i woud suggest to use "DDlCity.SelectedItem.Value" instead of " DDlCity.SelectedValue"
In your post back you can put the binding code in condition
if (!IsPostBack){
// Bind grid here looking for or used call to function something like BindGrid()
}
and in BindGrid() function you can write binding code for grid view.
and on ddl selected index changed event you can again call the BindGrid() method to bind again accordingly.
also check that in your dropdownlist you have EnablePostBack - true.

Categories