when I click the > on my GridView it does not go to the next set of records.
DataGrid dataGrid = new DataGrid();
dataGrid.PageSize = 5;
dataGrid.AllowPaging = true;
dataGrid.EnableViewState = true;
dataGrid.DataSource = customerDataTable;
dataGrid.AllowPaging ();
if (!IsPostBack)
{
dataGrid.DataBind();
}
Depending on my code, it either stays on the first 5 or the grid does not show.
I've tried the DataBind() in and out of the IsPostBack.
I've also tried adding
dataGrid.PageIndexChanged += new DataGridPageChangedEventHandler(dataGrid_PageIndexChanged);
and
void dataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
DataGrid dg = (DataGrid)source;
dg.DataBind();
}
But I can't get this to work. What am I doing wrong?
Thanks!
Here's an example I tried to recreate your scenario and it works. Check it out.
protected void Page_Load(object sender, EventArgs e)
{
GridView GridView1 = new GridView();
Panel1.Controls.Add(GridView1);
GridView1.DataSource = GetList();
GridView1.AutoGenerateColumns = true;
GridView1.EnableViewState = true;
GridView1.AllowPaging = true;
GridView1.PageSize = 4;
GridView1.DataBind();
GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);
}
void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (sender != null)
{
GridView GridView1 = sender as GridView;
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
}
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
}
private IEnumerable<Person> GetList()
{
List<Person> list = new List<Person>();
list.Add(new Person() {Age = 12, Name = "asdfsd"});
list.Add(new Person() {Age = 13, Name = "sdfsdaf"});
list.Add(new Person() {Age = 14, Name = "zxczxv"});
list.Add(new Person() { Age = 15, Name = "zxczxv" });
list.Add(new Person() { Age = 16, Name = "zxczxv" });
list.Add(new Person() { Age = 17, Name = "zxczxv" });
return list;
}
and in the markup all you need is to have the panel
<asp:Panel ID="Panel1" runat="server">
EDIT:
Here's the same scenario using DataGrid
protected void Page_Load(object sender, EventArgs e)
{
DataGrid dataGrid = new DataGrid();
Panel1.Controls.Add(dataGrid);
dataGrid.DataSource = GetList();
dataGrid.AutoGenerateColumns = true;
dataGrid.EnableViewState = true;
dataGrid.AllowPaging = true;
dataGrid.PageSize = 4;
dataGrid.DataBind();
dataGrid.PageIndexChanged +=new DataGridPageChangedEventHandler(dataGrid_PageIndexChanged);
}
void dataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
if (source != null)
{
DataGrid dataGrid = source as DataGrid;
dataGrid.CurrentPageIndex = e.NewPageIndex;
dataGrid.DataBind();
}
}
Related
currently this method is displaying in a gridview2 just the first column of the rows checked in gridview1 checkboxes but i need to display all of the columns exactly as gridview1, so how do i do it?
protected void Button1_Click2(object sender, EventArgs e)
{
List<string> lista = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("chk") as CheckBox;
if (chbox.Checked == true)
{
lista.Add("'" + GridView1.Rows[i].Cells[1].Text + "'");
}
}
DataTable dt = new DataTable();
GridView2.DataSource = lista;
GridView2.DataBind();
}
code to of your button will be below
protected void Button1_Click2(object sender, EventArgs e)
{
List<CopyGrid> lista = new List<CopyGrid>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("chk") as CheckBox;
if (chbox.Checked == true)
{
CopyGrid content = new CopyGrid();
content.Name = GridView1.Rows[i].Cells[1].Text;
content.Email = GridView1.Rows[i].Cells[2].Text;
content.City = GridView1.Rows[i].Cells[3].Text;
content.PostCode = GridView1.Rows[i].Cells[4].Text;
lista.Add(content);
}
}
// DataTable dt = new DataTable();
GridView2.DataSource = lista;
GridView2.DataBind();
}
also create one class that will store details of gridview1
public class CopyGrid
{
public string Name;
public string Email;
public string City;
public string PostCode;
}
This is just sample code you have to implement your own code.
After several searches on the Internet finally decided to drop a question.
At runtime I want the following to happen.
If you push a button a textbox will be added to the controls and a custom validator must be attached to the textbox and fire.
It does not fire. Why?
Here is my code
Thank you for looking into this.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
CustomValidator rv2 = new CustomValidator();
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rv2.ID = "rev2";
rv2.ErrorMessage = "Not numeric input";
rv2.ClientValidationFunction = "";
rv2.ServerValidate += new ServerValidateEventHandler(GetalValidator);
Controls.Add(rv2);
}
}
protected void ButtonClick(object sender, EventArgs args)
{
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
this.Controls.Add(tb1);`enter code here`
rv2.EnableClientScript = false;
rv2.ControlToValidate = "tb2";
}
private bool IsNumber(string someText)
{
int number;
bool result = Int32.TryParse(someText, out number);
return result;
}
protected void GetalValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = IsNumber(args.Value);
}
}
here is part of code thorugh which you can add validation on your dynamically created control.
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
RequiredFieldValidator regfv = new RequiredFieldValidator();
regfv.ID = "regfv";
regfv.ControlToValidate = tb1.ID;
regfv.ErrorMessage = "My Error";
this.Controls.Add(tb1);
this.Controls.Add(regfv);
I have a problem when I change dropdownlist1 item, The changed item not being accessed on the event of DropDownList1_SelectedIndexChanged.
Here is my code...
namespace My_News.Views.Shared
{
public partial class Master : System.Web.UI.MasterPage
{
SqlDataReader dr;
string user_id = "";
protected void Page_Load(object sender, EventArgs e)
{
/* user login information */
if (Session["status"] != null)
{
Button1.Text = "Logout";
Button2.Visible = true; ;
Button2.Text = Session["name"] as string + "'s Profile";
Button3.Enabled = true;
DropDownList1.Enabled = true;
user_id = Session["reg_id"] as string;
DropDownList1.Items.Clear();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DISTINCT[news_category] from [news_profile] WHERE [user_id]='" + user_id + "'";
cmd.Connection = connection;
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
connection.Close();
}
}
}
else
{
Button1.Text = "Login";
Button2.Visible = false;
Button3.Enabled = false;
DropDownList1.Enabled = false;
Session.Clear();
}
}
Dropdownnlist index change event...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["news_category"] = DropDownList1.Text;
Session["reload"] = "yes";
Session.Timeout = 10;
Response.Redirect("Default.aspx");
}
}
}
Please help me.
You need to modify your code like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindDDL();
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddl.Text;
}
public void bindDDL()
{
DataTable dt = new DataTable("Drop");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "ABCD");
dt.Rows.Add(2, "EFGH");
ddl.DataSource = dt;
ddl.DataValueField = "ID";
ddl.DataTextField = "Name";
ddl.DataBind();
}
I have a list in my SharePoint site with name "Empdetails" and having columns (EmpName string, Empaddress string).
I have to bind the list data to the SpGridview with edit, delete, update functionality.
I am able to bind the list data to gridview successfully, but I am unable to provide edit, delete, update functionality to the gridview.
Code:
private void binddata()
{
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["Empdetails"];
SPListItemCollection items = myList.Items;
//Here we will make a datatable and we will put our list data to the data table
DataTable table=new DataTable();
table.Columns.Add("EmpName", typeof(string));
table.Columns.Add("Empaddress", typeof(string));
// Create rows for each splistitem
DataRow row;
foreach (SPListItem result in items)
{
row = table.Rows.Add();
row["EmpName"] = result["EmpName"].ToString();
row["Empaddress"] = result["Empaddress"].ToString();
}
//binding data to gridview
GridView1.DataSource = table.DefaultView;
GridView1.DataBind();
}
You will need to write all of the code for updates and deletes. It is not provided automatically.
Personally, I would recommend using the out of the box List View web part that points to a Datasheet view rather than trying to create my own.
But if you must write custom code, your code above might be able to be simplified from this:
DataTable table = new DataTable();
table.Columns.Add("EmpName", typeof(string));
table.Columns.Add("Empaddress", typeof(string));
DataRow row;
foreach (SPListItem result in items)
{
row = table.Rows.Add();
row["EmpName"] = result["EmpName"].ToString();
row["Empaddress"] = result["Empaddress"].ToString();
}
to this:
DataTable table = items.GetDataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindata();
}
}
public void Bindata()
{
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["VisualWebpart"];
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
foreach (SPListItem item in list.Items)
{
DataRow dr = dt.NewRow();
dr["Title"] = item["Title"].ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void grd_Insert(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
SPWeb currentWeb = SPContext.Current.Web;
SPList lst = currentWeb.Lists["VisualWebpart"];
SPListItemCollection myColl = lst.Items;
TextBox txtTitle = (TextBox)GridView1.FooterRow.FindControl("txtTitle");
SPListItem item = myColl.Add();
item["Title"] = txtTitle.Text;
item.Update();
txtTitle.Text = "";
Bindata();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bindata();
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bindata();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int Title = row.DataItemIndex;
SPWeb currentWeb = SPContext.Current.Web;
SPList lst = currentWeb.Lists["VisualWebpart"];
SPListItemCollection myColl = lst.Items;
int itemcount = myColl.Count;
for (int i = 0; i <= itemcount-1; i++)
{
SPListItem item = myColl[i];
if (Title==i)
{
myColl.Delete(i);
}
}
Bindata();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int Title = row.DataItemIndex;
SPWeb currentWeb = SPContext.Current.Web;
SPList lst = currentWeb.Lists["VisualWebpart"];
SPListItemCollection myColl = lst.Items;
int itemcount = myColl.Count;
TextBox txtTit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTit");
string d = txtTit.Text;
for (int i = 0; i <= itemcount - 1; i++)
{
SPListItem item = myColl[i];
if (Title == i)
{
item["Title"] = d;
item.Update();
}
}
GridView1.EditIndex = -1;
Bindata();
}
}
I would like somebody to help me to solve the following issue.
I have a gridview, where the fields are created dynamically from codebehind.
I would like to create with the same way(dynamically) a templateField which, if it is possible, to hold in it two button controls, having also and commandName.
To be more clear:
Headers-->> First Name, LastName, Print(Daily/Invoices)
Results -->> FooFName, FooLName, Daily | Invoice
The bold one text is what I am looking for.
I am posting also the methods and the way I use them to create the fields.
CreateBoundField(BillingSummaryGV, "Book_Date", "Date", "{0:dd/MM/yyyy}");
CreateButtonField(BillingSummaryGV, "Print", "Print(Daily)", ButtonType.Link,"");
BillingSummaryGV.DataSource = billingSummaries;
BillingSummaryGV.DataBind();
protected void CreateBoundField(GridView gv, string dataField, string headerText, string arrFormatingString) {
var bf = new BoundField {
DataField = dataField,
DataFormatString = arrFormatingString,
HeaderText = headerText
};
gv.Columns.Add(bf);
}
private void CreateButtonField(GridView gv, string text, string headerText, ButtonType buttonType, string commandName) {
var bfPrint = new ButtonField() {
ButtonType = buttonType,
Text = text,
HeaderText = headerText,
Visible = true,
CommandName = commandName
};
gv.Columns.Add(bfPrint);
}
I would appreciate any reply
thanks
You have to create a template class that implements ITemplate. See this example from MSDN. The code below extends my answer to this question to add a template column that displays Title|Author.
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
CreateCustomTemplateField(GridView1, "Title|Author");
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
private void CreateCustomTemplateField(GridView gv, string headerText)
{
var customField = new TemplateField();
customField.HeaderTemplate = new CustomTemplate(DataControlRowType.Header, headerText);
customField.ItemTemplate = new CustomTemplate(DataControlRowType.DataRow, headerText);
gv.Columns.Add(customField);
}
public class CustomTemplate : ITemplate
{
private DataControlRowType _rowType;
private string _headerText;
public CustomTemplate(DataControlRowType rowType, string headerText)
{
_rowType = rowType;
_headerText = headerText;
}
public void InstantiateIn(Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
var header = new Literal();
header.Text = _headerText;
container.Controls.Add(header);
break;
case DataControlRowType.DataRow:
var data = new Literal();
data.DataBinding += DataRowLiteral_DataBinding;
container.Controls.Add(data);
break;
}
}
private void DataRowLiteral_DataBinding(object sender, EventArgs e)
{
var data = (Literal)sender;
var row = (GridViewRow)data.NamingContainer;
data.Text = DataBinder.Eval(row.DataItem, "Title") + "|" + DataBinder.Eval(row.DataItem, "Author");
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}