I am creating an asp.net / C# application with 2 pages.
The JavaScript on 1stPage.aspx will pass two parameters to the second page:
2ndPage.aspx?Paramter1=abc&Paramter2=xyz
2ndPage.aspx will fire a query to a SQL database and dynamically create a gridview.
I create 5 different gridviews on the same page dynamically with different IDs.
I want to pagenate gridview.
When I try to paginate, there is no change on the last 4 grids. Only pagination of first gridview is works properly.
I have tried to cache the dataview, but nothing seems to work.
C# CODE:
protected void Page_Load(Object Src, EventArgs E)
{
if (!IsPostBack)
{
string Param1= Page.Request.QueryString["Paramter1"];
string Param1 = Page.Request.QueryString["Paramter2"];
SqlDataAdapter cmdldata = new SqlDataAdapter("" + Param1 + " " + Param1, sqlconn);
DataView dataview_ldata;
GridView gv = new GridView();
ph.Controls.Add(gv);
gv.ID = "grid" + param1;
gv.AutoGenerateColumns = true;
gv.ShowFooter = false;
gv.CellPadding = 2;
gv.CellSpacing = 0;
gv.Font.Size = 11;
gv.EnableViewState = true;
gv.AllowPaging = true;
gv.PageSize = 10;
gv.RowStyle.Wrap = false;
gv.HeaderStyle.Wrap = false;
gv.PageIndexChanging += new GridViewPageEventHandler(gv_PageIndexChanging);
DataSet dsldata;
dsldata = new DataSet();
cmdldata.Fill(dsldata);
dataview_ldata = dsldata.Tables[0].DefaultView;
gv.DataSource = dataview_ldata;
gv.DataBind();
Cache["data"] = dataview_ldata;
ph.DataBind();
}//end of if IsPostBack
}//end of pageload
void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
gv.DataSource = (DataView)Cache["data"];
gv.DataBind();
}
HTML CODE:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder id="ph" runat="server" />
</div>
</form>
Related
I have 3 tasks:
Records should not repeat as showing like that image. output
When I click the button, It has to fetch the entire row records and the index of that particular row,
After clicking that button, I have to insert some records in the next row where user click the button.
For example: Totally 10 rows of records is in gridview. If user click second row button, it has to fetch the entire row details, index value of row and then insert 5 five rows of records from third row.
This is my code:
Sample.aspx
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>
Sample.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BoundField bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
GridView1.Columns.Add(bfield);
TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
GridView1.Columns.Add(tfield);
tfield = new TemplateField();
tfield.HeaderText = "Id";
GridView1.Columns.Add(tfield);
//BindGrid();
}
this.BindGrid();
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnRefresh_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
e.Row.Cells[1].Controls.Add(txtCountry);
Button lnkView = new Button();
lnkView.ID = "lnkView";
lnkView.Text = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[2].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
Button lnkView = (sender as Button);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[0].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
The most important thing is: I should get index of that row and insert the records between two records.
For your duplicate record concern: there's a property on GridView controls called AutoGenerateColumns. It defaults to true.
When it is true, all the columns/fields/properties in the data source will automatically appear as columns in the results. If you then add columns, those columns will appear in addition to (and after) the ones that are automatically generated.
This is easy to fix: change the AutoGenerateColumns property to false:
<asp:GridView ID="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="false"></asp:GridView>
If other problems are occurring, ask a separate question for those.
I have a Gridview with dropdownlist is created dynamically in OnRowDataBound event of gridview, initially I am setting a selected value.
The problem is when I switch to different index of dropdown its working fine but when I change to the default selected index the SelectedIndexChanged is not fired.
Kindly help me..
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList DropDownList1 = new DropDownList();
DropDownList1.ID = "DropDownList1";
DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
DropDownList1.EnableViewState = true;
DropDownList1.AutoPostBack = true;
DropDownList1.EnableViewState = true;
string sql1 = ".....";
DataTable dtDDL = new DataTable();
dtDDL = SQL.ReturnDataTable(sql1);
if (dtDDL.Rows.Count > 0)
{
DropDownList1.DataSource = dtDDL;
DropDownList1.DataTextField = "CODE";
DropDownList1.DataValueField = "CODE";
DropDownList1.DataBind();
DropDownList1.Font.Size = 8;
//DropDownList1.Items.Insert(0, new ListItem("0", "0"));
}
DropDownList1.SelectedValue = dtShift.Rows[0]["SHIFT_CODE"].ToString();
DropDownList1.ToolTip = dtShift.Rows[0]["ShiftTime"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//not coming here for default index changed
}
I have a PlaceHolder in a webform with Master page with the code
<asp:DropDownList ID="NoofSubjectList" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="NoofSubject_Index_Changed">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
<asp:PlaceHolder ID="placeholder" runat="server" />
Based on the number(n) selected from the DropDownList (1), I will be Dynamically creating two sets of DropDownList (2,3) for the selected n numbers. In that the first DropDownList loads data from a database. The code is shown below,
protected void NoofSubject_Index_Changed(Object sender, EventArgs e)
{
int value = Convert.ToInt32(NoofSubjectList.SelectedItem.Text.ToString());
DataSet ds1 = new DataSet();
MySql.Data.MySqlClient.MySqlConnection mysqlConnection = new
MySql.Data.MySqlClient.MySqlConnection
("Database=school;Server=localhost;UID=root;PWD=;");
MySql.Data.MySqlClient.MySqlCommand mysqlCommand = new
MySql.Data.MySqlClient.MySqlCommand
("SELECT Dept FROM tabledept WHERE Status='Active'", mysqlConnection);
MySql.Data.MySqlClient.MySqlDataAdapter mysqlAdaptor = new
MySql.Data.MySqlClient.MySqlDataAdapter(mysqlCommand);
mysqlAdaptor.Fill(ds1);
for (int i = 0; i <= value - 1; i++)
{
DropDownList _SubList = new DropDownList();
_SubList.ID = "SubList" + (i + 1);
_SubList.Width= 75;
DropDownList _DeptList = new DropDownList();
_DeptList.ID = "DeptList" + (i + 1);
_DeptList.Width = 75;
_DeptList.SelectedIndexChanged += DeptList_Index_Changed;
Literal _spacer = new Literal();
_spacer.Text = "<br />";
Literal _spacerlbl = new Literal();
_spacerlbl.Text = " ";
Label _Lbl = new Label();
_Lbl.ID = "lbl_Subject" + i;
_Lbl.Text = "Subject" + (i+1);
Label _Lbl1 = new Label();
_Lbl1.ID = "lbl_Dept" + i;
_Lbl1.Text = "Department";
_DeptList.DataSource = ds1;
_DeptList.DataTextField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataValueField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataBind();
_DeptList.AutoPostBack = true;
placeholder.Controls.Add(_Lbl1);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_DeptList);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_Lbl);
placeholder.Controls.Add(_SubList);
placeholder.Controls.Add(_spacer);
}
}
protected void DeptList_Index_Changed(Object sender, EventArgs e)
{
\\Based on the selection in DropDownList2, a list will be loaded from a
\\database to DropDownList3
}
The above event is triggered based on the selection of the number n from the DropDownList (1). If I select an item from DropDownList (2) the data will be generated from database and added to the DropDownList (3) . The problem is when I try to select an item from DropDownList (2), the dynamically created controls get lost. How to overcome this issue?
I even googled it and I found out that I am missing something called PostBack in my code. But I could not able to find out relevant resource to learn about it
I got a link which shows an easy example of creating the controls after postback.
Creating Dynamic TextBox Controls using C#
I have cached a select * query in a dataset in c#.
On my page I have 3 dropdownlists.
Depending on the dropdownlist selected I filter the datatable and bind it to the gridview.
whenever the data in the dropdownlist gets changed,I display the data accordingly.
My problem is, I have added pagination to this gridview since I have more than 500 results for each query.
When I try to paginate,the gridview disappears.The value in the dropdownlist does not change.
what should I do?
the code for page Index changing of gridview is:
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
thank you for you help in advance.
You need to bind your grid again in the function
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//provide data source here
GridView1.DataBind();
}
Following are the steps that may help you out...
Add dynamic gridview control to page or in any other control where u want to show it on page.
Set its pager settings along with PageIndexChanging Event Handler
Call it in OnInit Event instead of Page_Load
Following is sample code:
private void AddGridDynamically()
{
try
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell td = new HtmlTableCell();
GridView gv = new GridView();
gv.AllowPaging = true;
gv.PageSize = 20;
gv.PagerSettings.Visible = true;
gv.PagerSettings.Mode = PagerButtons.NumericFirstLast;
gv.PageIndexChanging += new GridViewPageEventHandler(gv_PageIndexChanging);
FillGrid(gv);
td.Controls.Add(gv);
tr.Cells.Add(td);
tbl1.Rows.Add(tr);
gv.EmptyDataText="No Data Found";
gv.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
private void FillGrid(GridView gv)
{
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Id");
DataRow dr;
for (int i = 0; i < 100; i++)
{
dr = dt.NewRow();
dr[0] = "AnyThing" + i;
dr[1] = i;
dt.Rows.Add(dr);
}
gv.DataSource = dt;
}
catch (Exception ex)
{
}
}
protected override void OnInit(EventArgs e)
{
AddGridDynamically();
}
I have tried a lot and have reached a dead end.
I have a to show multiple gridviews on one page and all these are getting populated dynamically.
i have figured a way to populate the gridview dynamically and display them, but i cannot get how to modify these values and display them as i want.
here is the code. for .aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:Panel ID="Panel1" runat="server" ScrollBars ="Auto" Height="500px" BorderColor="#003399" BorderWidth="3px">
</asp:Panel>
</asp:Content>
and here is the code for .aspx.cs
for (int j = 0; j < 5; j++)
{
GridView Grid = new GridView();
ArrayList machID = new ArrayList();
ArrayList machName = new ArrayList();
Grid.ID = machGrps[j].ToString();
Grid.AllowSorting = true;
Grid.CellSpacing = 2;
Grid.GridLines = GridLines.None;
Grid.Width = Unit.Percentage(100);
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(Session["ConnectionStringSQL"].ToString());
connection.Open();
SqlCommand sqlCmd = new SqlCommand("select MachineID, MachineName from Machines", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
connection.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
machID.Add(dt.Rows[i]["MachineID"].ToString());
machName.Add(dt.Rows[i]["MachineName"].ToString());
}
DataTable taskTable = new DataTable();
taskTable.Columns.Add("MachineID");
taskTable.Columns.Add("MachineName");
if (machID.Count != 0)
{
for (int i = 0; i < machID.Count; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["MachineID"] = machID[i];
tableRow["MachineName"] = machName[i];
taskTable.Rows.Add(tableRow);
}
}
Session["TaskTable"] = taskTable;
Grid.DataSource = Session["TaskTable"];
Grid.DataBind();
Label label = new Label();
label.Text = "Machine Grp" + Grid.ID;
Panel1.Controls.Add(label);
Panel1.Controls.Add(Grid);
}
}
NOTE THIS CODE BELOW CANNOT BE DONE ANYMORE AS I POPULATE THE GRIDVIEW DIRECTLY FROM THE TABLES:
I used to modify like this when the ondatabound="GridView1_DataBound" if is called from the .aspx page
the databound code looks like this:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow myRow in GridView1.Rows)
{
//this is where ID is stored in an label template
Label Label3 = (Label)myRow.FindControl("Label3");
int val = Convert.ToInt32(Label3.Text);
Image Image5 = (Image)myRow.FindControl("Image5");
if (Convert.ToInt32(Label3.Text) < 0)
{
Image5.ImageUrl = "~/NewFolder1/warning_16x16.gif";
}
else
{
Image5.ImageUrl = "~/NewFolder1/1258341827_tick.png";
}
}
}
Two things:
protected void GridView1_DataBound(object sender, EventArgs e) {
foreach (GridViewRow myRow in GridView1.Rows) {
// blah blah blah code goes here
}
}
should be
//now e is a
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
// blah blah blah, this lets you work on one row at a time.
// since the framework does this per row, you don't need to parse the gridview
// yourself, altho you're more than welcome to.
// But you can get more control this way. I promise.
Label Label3 = (Label)e.Row.FindControl("Label3");
int val = Convert.ToInt32(Label3.Text);
Image Image5 = (Image)e.Row.FindControl("Image5");
if (val < 0)
{
Image5.ImageUrl = "~/NewFolder1/warning_16x16.gif";
}
else
{
Image5.ImageUrl = "~/NewFolder1/1258341827_tick.png";
}
// alternately write the code above like this:
Image Image5 = (Image)e.Row.FindControl("Image5");
Image5.ImageUrl = (val < 0) ? "~/NewFolder1/warning_16x16.gif" : "~/NewFolder1/1258341827_tick.png";
// that's called the ternary operator. Takes up less space, does the same thing.
}
}
Please don't ignore this part
Now to the other part, are you aware that you can still bind in the backside like thus:
GridView1.RowDataBound += GridView1_RowDataBound;
Put it here:
for (int j = 0; j < 5; j++)
{
GridView Grid = new GridView();
ArrayList machID = new ArrayList();
ArrayList machName = new ArrayList();
//NEW LINE (doesn't need the comment or the blank space tho)
Grid.RowDataBound += Grid_RowDataBound;
Grid.ID = machGrps[j].ToString();
Grid.AllowSorting = true;
Grid.CellSpacing = 2;
Grid.GridLines = GridLines.None;
Grid.Width = Unit.Percentage(100);
Do your dynamic edits on GridView1_RowDataBound not on GridView1_DataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label Label3 = (Label)e.Row.FindControl("Label3");
....
}
}
Is it blowing up when you're binding the DataSource to the Session object?
Grid.DataSource = taskTable;