Programmatically bind List<String> to GridView - asp.net

Just trying a simple bind. No values are populated into the GridView however.
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
list.Add("Bread");
list.Add("Cheeze");
list.Add("Wine");
list.Add("Beer");
list.Add("Waffles");
GridView1.DataSource = list;
GridView1.DataBind();
}

Did you set AutoGenerateColumns to true?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />

another approach
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
list.Add("Bread");
list.Add("Cheeze");
list.Add("Wine");
list.Add("Beer");
list.Add("Waffles");
GridView1.DataSource = list;
GridView1.DataBind();
GridView1.Columns.Add(new BoundField());
}

Related

ASP.net gridview paging index disappear when i change the page index

this is my code : when i change the index of pager i get the right data but the pager footer disapear :
<asp:GridView ID="GridView1" runat="server" PageSize="4" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" OnRowEditing="GridView1_RowEditing" DataKeyNames="id" OnRowCancelingEdit="GridView1_RowCancelingEdit" AlternatingRowStyle-CssClass="eventRowStyle" OnPageIndexChanging="GridView1_PageIndexChanging" OnPageIndexChanged="GridView1_PageIndexChanged">
Codebehind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewDBEntities model = new GridViewDBEntities();
var query = from p in model.userTbls select p;
GridView1.DataSource = query;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewDBEntities model = new GridViewDBEntities();
var query = (from p in model.userTbls orderby p.id ascending select p).Skip((e.NewPageIndex) * GridView1.PageSize).Take(GridView1.PageSize);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = query;
GridView1.DataBind();
}
You can force your Pager to remain visible !
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView1.BottomPagerRow.visible = True
BTW you have already defined pageSize and set Paging to true so i think this will do
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
GridViewDBEntities model = new GridViewDBEntities();
var query = from p in model.userTbls select p;
GridView1.DataSource = query;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// GridViewDBEntities model = new GridViewDBEntities();
// var query = (from p in model.userTbls orderby p.id ascending select //p).Skip((e.NewPageIndex) * GridView1.PageSize).Take(GridView1.PageSize);
GridView1.PageIndex = e.NewPageIndex;
// GridView1.DataSource = query;
//GridView1.DataBind();
BindGrid();
}
Removing !IsPostback will cause problems later if you have to implement some functionality where you have to edit grid or insert records , Either way better will be to create a Bind method and use it according to requirements .

Asp.net GridView Enabling row selection

I am using GridView in asp.net. I want to select a single data row. I looked for MultiSelect and SelectionMode in property panel, but I can't find it.
So how to enable selecting rows in GridView?
Thanks.
Code Behind
public partial class SearchCourse : System.Web.UI.Page
{
Connection dbCon;
DataTable tbl;
protected void Page_Load(object sender, EventArgs e)
{
dbCon = new Connection();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked) {
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled =false;
txtSubName.Text = "";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) {
comboProgram.Enabled = true;
if (comboProgram.SelectedItem.ToString() == "Foundation Course")
{
comboSemester.Enabled = false;
comboYear.Enabled = false;
}
else {
comboSemester.Enabled = true;
comboYear.Enabled = true;
}
txtSubName.Text = "";
txtSubName.Enabled = false;
}
}
protected void imgBtnSearch_Click(object sender, ImageClickEventArgs e)
{
if (RadioButton1.Checked) {
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectName(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton2.Checked)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem= comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program,year,sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton3.Checked)
{
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectNo(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year, sem;
if (program == "Foundation Course")
{
comboYear.Enabled = false;
comboSemester.Enabled = false;
year = null;
sem = null;
}
else {
comboYear.Enabled = true;
comboSemester.Enabled = true;
year = comboYear.SelectedItem.ToString();
sem = comboSemester.SelectedItem.ToString();
}
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboYear_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboSemester_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled = false;
txtSubName.Text = "";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
GridView Code
<asp:GridView ID="GridView1" CssClass="grid" runat="server" AllowPaging="True"
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
GridLines="Horizontal" EnableViewState="False"
PageSize="5" onselectedindexchanged="GridView1_SelectedIndexChanged" >
<RowStyle CssClass="gridRow" Width="800px" />
<SelectedRowStyle BackColor="#FF0066" ForeColor="White" />
</asp:GridView>
I think the MultiSelect and SelectionMode properties are only available with the VB.NET grid, not in ASP.NET. Bear in mind that all controls in ASP.NET are HTML-in-disguise, so they may be more limited. There is no reason why you can't have a multi-select table, but you have to do the plumbing yourself. So you need to enable row selection, either by handling the RowDataBound event as in
http://forums.asp.net/t/992062.aspx?How+to+select+row+in+gridview+on+click
or else using the MS-provided option as in
http://msdn.microsoft.com/en-us/library/wbk82279(v=vs.100).aspx
Then you need to handle the SelectedIndexChanging event, figure out which row the user clicked on, and handle the row-colouring yourself.
This problem is still actual for me 9 years later.
In As?x code I added SelectedRowStyle and asp:CommandField blocks:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<SelectedRowStyle BackColor="#337ab7" ForeColor="White" />
<Columns>
<asp:CommandField SelectText="Select" ShowSelectButton="True">
<HeaderStyle Width="50px" />
</asp:CommandField>
Code behind:
protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
}
In gridview you have to define an event onselectedindexchanged and onrowdatabound as below:
onselectedindexchanged="GridView1_SelectedIndexChanged" onrowdatabound="GridView1_RowDataBound"
to show the selected row you can use following style in your grid view:
<SelectedRowStyle BackColor="Red" />
in code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
// The seelctButton exists for ensuring the selection functionality
// and bind it with the appropriate event hanlder.
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text
};
selectButton.Font.Underline = false;
selectButton.ForeColor = Color.Black;
e.Row.Cells[0].Controls.Add(selectButton);
//e.Row.Attributes["OnClick"] =
// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
note: you can find the event in event window.

manual gridview paging

i'm am pulling 10 out of 100 records back from the database and placing into gridview (no datasource objects here).
how do i enable paging that comes with the gridview? I know the total records is 100 can I use that somehow to activate the paging?
I know I can do this easily with DataSource objects but was just wondering if I could do it completely manually as far as the GridView is concerned.
Markup
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting">
</asp:GridView>
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
strong text
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback) {BindData();}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
void BindData()
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
Also you need to add this to gridview markup:
OnPageIndexChanging="GridView1_PageIndexChanging"

modify datarow value for a specific gridview column

how would i change the value IBM to something arbitrary like Cisco in one of the gridview events listed?
there can be varying columns in the dynamic gridview so would be nice to address the column by name.
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("TestTable");
dt.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("customername") });
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Microsoft";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2[0] = "2";
dr2[1] = "IBM";
dt.Rows.Add(dr2);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
}
}
This won't work when AutogenerateColumns is set to true(default). You need to add the columns programmatically or declaratively(in aspx markup). Then you can use a TemplateField with a Control like Label that you can reference in codebehind:
For example:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" runat="server">
<Columns>
<asp:TemplateField HeaderText="Customer">
<ItemTemplate>
<asp:Label ID="LblCustomer" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
RowDataBound is perfect(for almost everything):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) {
var row = ((DataRowView)e.Row.DataItem).Row;
var lblCustomer = (Label)e.Row.FindControl("LblCustomer");
var customerName = row.Field<String>( "customername" );
if(customerName == "Microsoft") {
customerName = "Cisco";
}
lblCustomer.Text = customerName;
}
}
Edit: Ok, never needed to do such. But actually you can change the Microsoft values to Cisco even with AutoGenerateColumns set to true.
DataBinding event is triggered before the GridView is databound. If you change the datasource before it's bound to grid, you'll be able to modify it:
protected void GridView1_DataBinding(object sender, EventArgs e)
{
var tbl = (DataTable)((GridView)sender).DataSource;
var msRows = tbl.AsEnumerable()
.Where(r => r.Field<String>("customername") == "Microsoft")
.Select(r => r);
foreach(DataRow msRow in msRows) {
msRow[ "customername" ] = "Cisco";
}
}
Note: of course you can also use a simple loop instead of LINQ

I want RowCommand executed before RowCreate reloading OR something like this

I have
<asp:GridView>
<asp:TemplateField HeaderText="PsyHealth">
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="PsyHealth" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="-">
<ItemTemplate>
<asp:LinkButton ID="Gen" CommandName="Gen" runat="server" Text="gen" />
</ItemTemplate>
</asp:TemplateField>
and
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dataItem = e.Row.DataItem as ViewModels.UserTestorViewModel;
var psyHealth = e.Row.FindControl("PsyHealth") as PlaceHolder;
if (psyHealth != null)
{
psyHealth.Controls.Add(dataItem.PsyHeath);
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//bla bla bla
}
but when I clicked the Gen LinkButton on the page. The GridView1_RowCreated was triggered first and threw the error Object reference not set to an instance of an object because the e.Row.DataItem was null.
Edit: The Code Behind
protected void Page_Load(object sender, EventArgs e)
{
List<ViewModels.UserTestorViewModel> utViewModelList = new List<ViewModels.UserTestorViewModel> { };
utViewModelList = utRepo.GetUserTestorViewModelListByHrId();
this.GridView1.DataSource = utViewModelList;
this.GridView1.DataBind();
if (!IsPostBack)
{
}
}
protected void Page_Init(object sender, EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}
Can you store the utViewModelList in Session first time you get it? If so then you can get the UserTestorViewModel instance from saved by the selected row's DataKey value.
When you click any button in the gridview , your page is postbacked and the page load event is called before it goes into the RowCommand event. In the page load event you are binding your gridview again and that's why your RowCreated Event is called.
You have to bind your gridview under if (!IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ViewModels.UserTestorViewModel> utViewModelList = new List<ViewModels.UserTestorViewModel> { };
utViewModelList = utRepo.GetUserTestorViewModelListByHrId();
this.GridView1.DataSource = utViewModelList;
this.GridView1.DataBind();
}
}
Edit: Now I got your issue after you posted code..
The problem is here in Page_Init, can you remove the event handler from here and try the following:
protected void Page_Init(object sender, EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
}
add here
<asp:GridView onrowcreated="GridView1_RowCreated">

Resources