link in gridview to details page - asp.net

What I'm trying to do is create a Gridview and in the grid have a HyperLinkField it send me to a detail page for that item, I have the part that filled the grid and the link and how to pass the id of the element to another page
The problem I have is that when I run and click on the link shows me the details page that I want but is blank. when I debugged, I don't reach the details page
here is my code
fill the grid
var datos = db.Ticket
GridView1.DataSource = datos;
GridView1.DataBind();
show the GridView
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperLinkField HeaderText="Ver Ticket" Text="Ir Historial Ticket" DataNavigateUrlFormatString="~/DetailTicket.aspx?id={0}" DataNavigateUrlFields="IdTicket" />
</Columns>
</asp:GridView>
the detail page
public partial class DetailTicket: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
var id= Request.QueryString["id"];
var datos = db.detailTicket.Where(e=>e.IdTicket==id)
GridView1.DataSource = datos;
GridView1.DataBind();
}
}

Hey it might be issue with your path...
I have test your code and its working fine with me....

You are missing brackets on the if statement in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
var id= Request.QueryString["id"];
var datos = db.detailTicket.Where(e=>e.IdTicket==id)
GridView1.DataSource = datos;
GridView1.DataBind();
}
}
Without the brackets, your id variable will not be known on the next line. I'd be surprised if it even compiles.

Related

Implementing search page

I'm new to ASP.Net and trying to implement a search page in my project.
I created a simple search.aspx
<asp:TextBox runat="server" ID="txtSearch" MaxLength="250"/>
<asp:LinkButton ID="lnkSearch" runat="server" Text="Search" OnClick="Search_Click" ClientIDMode="Static" />
<asp:Repeater ID="rep" runat="server" >
....
</asp:Repeater>
and the search.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Text = Request.Params["q"].ToString();
BindRepeater(); //reads Request.Params["q"] and fetches data
txtSearch.Focus();
this.Page.Form.DefaultButton = this.lnkSearch.UniqueID;
}
protected void Search_Click(object sender, EventArgs e)
{
Response.Redirect("/Search.aspx?q=" + txtSearch.Text);
}
Problem is that when I type something in txtSearch and hit enter or click search, the page reloads with the old query string and old search results, seems that txtSearch.Text is updated with old Query value before hitting Search_Click
For Example if I enter search.aspx?q=apple in address bar the page returns correct results and txtSearch's Text = "apple" .. if I type green apple and hit enter, page returns apple results, and txtSearch's Text = "apple", also the link is search.aspx?q=apple
I tried
AutoPostBack="True|False" for the TextBox
if (!IsPostBack)
txtSearch.Text = Request.Params["q"].ToString();
but I can't use it I guess since I'm posting back to same page, no?
I also tried
if (IsPostBack && txtSearch.Text != Request.Params["q"].ToString())
txtSearch.Text = Request.Params["q"].ToString();
This seems a strange way of doing it to me.
My preference would be to have the search logic in the event handler itself, rather than implementing this strange post-back loop.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
// If passed in on first entry to the page
var searchQuery = Reqest.Params["q"];
if (String.IsNullOrWhitespace(searchQuery) == false)
{
txtSearch.Text = searchQuery;
Search_Click(null, null);
}
}
txtSearch.Focus();
this.Page.Form.DefaultButton = this.lnkSearch.UniqueID;
}
protected void Search_Click(object sender, EventArgs e)
{
// Pass the value of the search to the repeater
BindRepeater(txtSearch.Text);
}
Note that I'm passing the search text to BindRepeater so you'd have to update it to use the parameter value rather than query string

Dropdown Selected IndexChanged is not firing

I have one dropdownlist and its autopostback property is set to true.But when value is changed the selectedindexchanged property is not fired instead it is always going to pageload.Please tell what is the issue.
<asp:DropDownList ID="ddlVendor" CssClass="ddl" runat="server"
OnSelectedIndexChanged="ddlVendor_SelectedIndexChanged" AutoPostBack="true">
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
List<ProcurementItem> vendorsList = new List<ProcurementItem>();
vendorsList = (List<ProcurementItem>)ViewState["VendorList"];
string ID = string.Empty;
string accountID = string.Empty;
int? accountType = null;
if (ddlVendor.SelectedIndex > 0)
{
ID = ddlVendor.SelectedValue;
ProcurementClient procurementClient = new ProcurementClient();
List<ProcurementContract> contractList =
procurementClient.GetContractList(Convert.ToInt32(ID), null);
contractList = contractList.Where(i => i.Status == 4).ToList();
ddlContracts.DataSource = contractList;
ddlContracts.DataTextField = "ContractIDName";
ddlContracts.DataValueField = "ContractID";
ddlContracts.DataBind();
ddlContracts.Items.Insert(0, "");
}
}
Add following property in DropDownList
1.ViewStateMode="Enabled"
2.EnableViewState="true"
3.AutoPostBack="true"
try this
<asp:dropdownlist id=ddltrim width="100%" Runat="server" AutoPostBack="True" EnableViewState="True" onselectedindexchanged="ddltrim_SelectedIndexChanged">
Make Sure That your DropDownList within the Fom tag
<form>
//
</form>
dear check the causesvalidation= false
may be this is the problem
if you have any validations in your page dear
Thanks
:D
If you are filling the dropdown list from database then, make sure that the DataBind() method of dropdown list is called only when its not a post back as...
protected void Page_Load(object sender, EventArgs e)
{
...
If(!Page.IsPostBack)
{
......
dropdownlist.DataBind();
.....
}
...
}
Hope this helps :)

The GridView 'GridView1' fired event PageIndexChanging which wasn't handled

I have created:
one master page and one content page called Detail.
On Button click event, displaying data in grid view.
In grid view, columns are autogenerated.
I wanted to show 11 column in grid view, but it is more than page
size.
What to do for this?
I have created sql helper file for database connection code and calling that method, not using sqldatasource for connection.
When I trying to do paging, getting error:
The GridView 'GridView1' fired event PageIndexChanging which wasn't
handled.
You need to declare a method on your code behind that handles the PageIndexChanging event.
Something similar to this:
protected void GridView1_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView(); //bindgridview will get the data source and bind it again
}
private void bindGridView()
{
GridView1.DataSource=getData();
GridView1.DataBind();
}
Providing sample code:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView(); //bindgridview will get the data source and bind it again
}
protected void Page_Load(object sender , EventArgs e)
{
if(!IsPostBack)
bindGridView();
}
//this is some sample data
private void bindGridView()
{
DataTable t = new DataTable();
t.Columns.Add("Col1");
t.Columns.Add("Col2");
DataRow r = null;
for (int i = 0; i < 25; i++)
{
r = t.NewRow();
r.ItemArray = new object[] { "Val" + i, " Another " + i };
t.Rows.Add(r);
}
GridView1.DataSource = t;
GridView1.DataBind();
}
And this is the markup:
<asp:GridView OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging="true" PageSize="10" ID="GridView1" runat="server" AutoGenerateColumns="true">
Produces this:
For Paging you can use OnPageIndexChanging for this....
For Example
you have to use OnPageIndexChanging="gvdetails_PageIndexChanging" in your GridView...
You have to write below code into event in code behind like
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvdetails.PageIndex = e.NewPageIndex;
BindData();
}
For more detail you can check the below link here I am using page Index change in my article...
Here I use PageIndexChange
I hope this will helps you....Share it with others...Thanks!
This is the final answer:
Imports System.Collections.Generic ' library
Protected Sub grdEmployees_PageIndexChanging1(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdEmployees.PageIndexChanging
grdEmployees.PageIndex = e.NewPageIndex
LoadEmployeeList() 'FUNCTION FOR DATASET
grdEmployees.DataBind()
End Sub
you simply add this to your code :
protected void GridViewTrsEmail_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewTrsEmail.PageIndex = e.NewPageIndex;
GridViewTrsEmail.DataBind();
}
To fix this, I had to take a closer look at my datasource and datakeys. I have a set of records that are returned from SQL Server and what I was doing is binding them to a POCO. This class had several public properties of type Integer. These Integers were my datakeys on the grid. I replaced their type with a string instead to bypass the casting issue.

Paging ObjectDataSource

My ASP page code:
<asp:ObjectDataSource runat="server" ID="odsResults" OnSelecting="odsResults_Selecting" />
<tr><td>
<wssawc:SPGridViewPager ID="sgvpPagerTop" runat="server" GridViewId="sgvConversionResults" />
</td></tr>
<tr>
<td colspan="2" class="ms-vb">
<wssawc:SPGridView
runat="server"
ID="sgvConversionResults"
AutoGenerateColumns="false"
RowStyle-CssClass=""
AlternatingRowStyle-CssClass="ms-alternating"
/>
</td>
</tr>
Class code:
public partial class Convert : System.Web.UI.Page
{
...
private DataTable resultDataSource = new DataTable();
...
protected void Page_Init(object sender, EventArgs e)
{
...
resultDataSource.Columns.Add("Column1");
resultDataSource.Columns.Add("Column2");
resultDataSource.Columns.Add("Column3");
resultDataSource.Columns.Add("Column4");
...
odsResults.TypeName = GetType().AssemblyQualifiedName;
odsResults.SelectMethod = "SelectData";
odsResults.SelectCountMethod = "GetRecordCount";
odsResults.EnablePaging = true;
sgvConversionResults.DataSourceID = odsResults.ID;
ConversionResultsCreateColumns();
sgvConversionResults.AllowPaging = true;
...
}
protected void btnBTN_Click(object sender, EventArgs e)
{
// add rows into resultDataSource
}
public DataTable SelectData(DataTable ds,int startRowIndex,int maximumRows)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3");
dt.Columns.Add("Column4");
for (int i =startRowIndex; i<startRowIndex+10 ;i++)
{
if (i<ds.Rows.Count)
{
dt.Rows.Add(ds.Rows[i][0].ToString(), ds.Rows[i][1].ToString(),
ds.Rows[i][2].ToString(), ds.Rows[i][3].ToString());
}
}
return dt;
}
public int GetRecordCount(DataTable ds)
{
return ds.Rows.Count;
}
protected void odsResults_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["ds"] = resultDataSource;
}
}
On clicking the button resultDataSource receives some rows. Page reload and we can see result in sgvConversionResults. First 10 rows. But after click next page in pager we have message "There are no items to show in this view". When I try debug I find that after postBack page (on click next page) input params "ds" is blank, ds.Rows.Count = 0 and etc... As though resultDataSource became empty((
What did I do incorrectly?
onPostBack all variables get default values, sgvConversionResults save her structure but has clear rows. How I can save sgvConversionResults data onPostBack event???
Maybe try:
protected void Page_Load(object sender, EventArgs e)
{
sgvConversionResults.DataBind();
}
Your code seems a bit convoluted though, any particular reason you are using an ObjectDataSource? Cause you can bind the datatable directly to the gridview in the codebehind
I transmit resultDataSource with ViewState and this work success!

How do I disable the select button text in a gridview after clicking it once? (ASP.NET)

as the title says, How do I disable the select button text in a gridview after clicking it once? I want to click it once, then have the select cell area render an image (and the image not clickable or linking to anything).
Any ideas?
protected void Page_Load(object sender, EventArgs e)
{
dn = new holdDataContext();
if (!(Page.IsPostBack))
{
// GridView1.DataSource = dn.tennis.ToList();
// GridView1.DataBind();
GridView1.DataSource = from c in dn.tennis
orderby c.ID descending
select c;
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = null;
if (Session["oro"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Description"));
ds.Tables.Add(dt);
Session["oro"] = ds;
}
else
{
ds = (DataSet)Session["oro"];
}
DataRow row = ds.Tables[0].NewRow();
row["Name"] = GridView1.Rows[GridView1.SelectedIndex].Cells[2].Text;
row["Description"] = GridView1.Rows[GridView1.SelectedIndex].Cells[3].Text;
ds.Tables[0].Rows.Add(row);
}
you'll need a combination of aspx markup and code-behind:
aspx:
<asp:GridView ID="gvSample" runat="server"
DataKeyNames="CustomerID"
onselectedindexchanged="gvSample_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnSelect" runat="server" CommandName="Select" Text="Select"></asp:LinkButton>
<asp:Image ID="imgSelect" runat="server" ImageUrl="~/imgs/whatever.jpg" Visible="false" />
</ItemTemplate>
code-behind:
protected void gvSample_SelectedIndexChanged(object sender, EventArgs e) {
LinkButton linkButton = gvSample.SelectedRow.Cells[0].FindControl("btnSelect") as LinkButton;
Image imgWhatever = gvSample.SelectedRow.Cells[0].FindControl("imgSelect") as Image;
linkButton.Enabled = false;
linkButton.Visible = false;
imgWhatever.Visible = true;
}
so, in the ItemTemplate markup of the GridView, specify the image you want to replace the Select button with but make it invisible, then disable the Select button in place of the image by swapping visibility between both objects within the event handler method gvSample_SelectedIndexChanged in the code-behind, which is what gets triggered upon clicking Select button. Since FindControl returns objects of type Control you'll have to cast to the LinkButton type of your Select button.

Resources