protected void GridviewArchived_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridviewArchived.PageIndex = e.NewPageIndex;
DisplayArchivedNews();
}
private void DisplayArchivedNews()
{
using (SqlConnection Con = new SqlConnection(connection1))
{
SqlCommand Cmd = new SqlCommand("udspGetArchivedNews", Con);
Cmd.CommandType = CommandType.StoredProcedure;
Con.Open();
Cmd.ExecuteNonQuery();
Con.Close();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(Cmd);
da.Fill(ds);
DataTable dt = ds.Tables[0];
int totalrecord = ds.Tables[0].Rows.Count;
GridviewArchived.DataSource = ds;
GridviewArchived.DataBind();
if (totalrecord > 0)
{
for (int i = 0; i < totalrecord; i++)
{
if( File.Exists(Server.MapPath("~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString().ToString() + (".PDF"))))
{
HyperLink link = new HyperLink();
link.Text = "Page1";
link.Target = "blank";
link.NavigateUrl = "~//NewsFolder//Page1//" + GridviewArchived.DataKeys[i].Values["News_ID"].ToString() + (".pdf");
GridviewArchived.Rows[i].Cells[2].Controls.Add(link);
}
}
}
}
}
Pagesize is 10, but when total record count is greater than pagesize it throws the following exception:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.
What is the solution so that record will automatic goes to next pageindex?
For showing record of a gridview in paging there are two options for that
One you can add an object datasource with your gridview and show paging through it and the other option is to use jquery Datatable for paging.
Related
I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}
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;
}
I am writing a project in ASP.net which I have six text boxes to display the information of the next record in my database. And I also have a search button base on some selected field which will search out my first record in my database. I inserted the code for my first record into the search button event handler. The code is written below:
Using System.Data;
Using System.Data.OleDb;
Using System.IO;
OleDbconnection mycon = new OleDbconnection("");
protected void search_btn_Click(object sender, EventArgs e)
{
int i = 0;
DataTable dt;
String searchme = "select * from student where myclass = '" + txtclass.Text + "' and mytype = '" + txtclasstype.Text + "'";
OleDbCommand cmd = new OleDbCommand (searchme, mycon);
mycon.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count > 0)
{
i = 0;
txtsearbox.Text = dt.Rows[i]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[i]["surname"].ToString();
txtfirstname.Text = dt.Rows[i]["firstname"].ToString();
txtothername.Text = dt.Rows[i]["othername"].ToString();
txtsex.Text = dt.Rows[i]["sex"].ToString();
Photo.ImageUrl = dt.Rows[i]["photo"].ToString();
// then I created a session to hold my dt.
Session["dt"] = dt;
}
mycon.Close();
}
The above code is working fine for my first record but where I am having problem is from my next button which is written as shown below:
protected void next_btn_Click(object sender, EventArgs e)
{
int rowIndex = 0;
rowIndex ++;
if(rowIndex <= dt.Rows.Count)
{
txtsearbox.Text = dt.Rows[rowIndex]["Admin_no"].ToString();
txtsurname.Text = dt.Rows[rowIndex]["surname"].ToString();
txtfirstname.Text = dt.Rows[rowIndex]["firstname"].ToString();
txtothername.Text = dt.Rows[rowIndex]["othername"].ToString();
txtsex.Text = dt.Rows[rowIndex]["sex"].ToString();
Photo.ImageUrl = dt.Rows[rowIndex]["photo"].ToString();
}
mycon.Close();
}
The error it shows is: There is no row at position 1.
I have a datalist which contain product catagory with unique ID asign to every products in my catalog. However, when i checked 2 or more checkboxes, i will only get the latest data display next page, but not all the data displayed. Just 1 data displayed only. Is there any way i can do so that I can pass 3 different ID at a time and display on nxt page?
void GetCheckedBox()
{
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
string url = "CompareProducts.aspx?prodId=" + cb.Value.ToString();
Response.Redirect(url);
}
}
}
CompareProducts.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID = #ProdID", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.Parameters.AddWithValue("#ProdID", Page.Request.QueryString["ProdID"].ToString());
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}
I'm not totally sure what you are saying, but based on your code I see in your ForEach loop you have a response.redirect, so in this case you will only redirect to a single ID querystring. You could switch your to use a session variable that holds a list of all the ID's the user selected.
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
}
Session.Add("SelectedProducts", Product);
string url = "CompareProducts.aspx?hasProducts=true;
Response.Redirect(url);
}
Then in your CompareProducts.aspx.cs on pageload if not postback check the querystring to decide if you should load the id's.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Page.Request.QueryString["hasProducts"].ToString() == "true")
{
ArrayList al = Session["SelectedProducts"] as ArrayList;
if (al == null)
throw new ApplicationException("A product list is required.");
if (al.Count < 1)
throw new ArgumentException("No products selected");
string inStatement = string.Empty;
foreach (var item in al)
{
inStatement += al.ToString() + ", ";
}
inStatement = inStatement.Substring(0, inStatement.Length - 2);
//Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID in (" + inStatement + ")", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}
This value (val1) I'm passing through url (I mean this operation as jobong filter option in checkbox list, filtering by selection index then passing through another page and retrieve through database):
Default Page 3: /WebSite4/Default4.aspx?vaL1=blue,red
This retrieving form page to view in page.
Default Page 2:
public void grid()
{
con.Open();
cmd = new SqlCommand("select * from lady_cloth where color in('" + Request.QueryString["vaL1"] + "')", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataSet ds3 = new DataSet();
da1.Fill(ds3);
con.Close();
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
SqlConnection con = new SqlConnection("Data Source=xxxx;Initial Catalog=e_commerce;User ID=sa;Password=xxx");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Label1.Text = Request.QueryString["Item"];
//Label2.Text = Request.QueryString["Color"];
//grid();
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
}
string sql = "SELECT * FROM lady_cloth WHERE color IN (SELECT Value FROM #Colours)";
cmd = new SqlCommand(sql, con);
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
//parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
con.Open();
adapter.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
I think your problem is that you are not separating your items, so your SQL ends up looking like:
select *
from lady_cloth
where color in('blue,red')
Whereas what you would really want is
select *
from lady_cloth
where color in('blue','red')
If you are using SQL Server 2008 or later then I would recommend using table-valued parameters. The first step would be to create your type:
CREATE TYPE dbo.StringList TABLE (Value NVARCHAR(MAX));
I tend to just create generic types that can be easily reused, but this would be your call.
Then in your method you would need to split your values into an array and add them to a datatable:
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
You can then add this table to your command as a parameter:
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
cmd = new SqlCommand(sql, con);
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
Finally, You can reduce your code by just initialising the SqlDataAdapter with your SQL and connection:
public void grid()
{
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
adapter.Parameters.Add(parameter);
con.Open();
da1.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}