GridView getting the data trough the id asp.net - c#

The problem really is that i do can trough the selects on the gridview get the data trough the id, but then i use the search option i implemented on the page and the gridview shows the ones it gets that match the result but if i press select it will redirect to the page with the wrong id, isntead of getting the id of the one i selected it gets the id of the field that was on the 1st position of the cell.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
TeamGest.DBLayer.DBLTeams dbl = new TeamGest.DBLayer.DBLTeams();
GridView1.DataSource = dbl.List();
GridView1.DataBind();
TeamGest.DBLayer.DBLPlayers dbl1 = new TeamGest.DBLayer.DBLPlayers();
GridView2.DataSource = dbl1.List();
GridView2.DataBind();
}
protected void MyMenu_MenuItemClick(object sender, MenuEventArgs e)
{
{
MyMultiView.ActiveViewIndex = Int32.Parse(e.Item.Value);
int i;
for (i = 0; i <= MyMenu.Items.Count - 1; i++)
{
if (i == Convert.ToInt32(e.Item.Value))
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
else
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Redirect("DetalhesClube.aspx?Id="+row.Cells[0].Text);
}
protected void Button1_Click1(object sender, EventArgs e)
{
string searchStringTeam = TextBox1.Text;
GetTeamResults(searchStringTeam);
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Response.Redirect("DetalhesJogador.aspx?Id=" + row.Cells[0].Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
string searchStringPlayer = TextBox2.Text;
GetPlayerResults(searchStringPlayer);
}

Don't use the cell values. That's what the DataKeys collection is for:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID, SomeOtherColumn" ...>
And in code-behind all you need is the row index:
var rowIndex = 0;
var ID = (int)GridView1.Rows[rowIndex]["ID"];

Related

dropdown list goes back to first value after selected index changes

I have a drop down list with a button event that should send it's value for a textbox.But,even if I choose a value that is not the first one in the DDL,it only sends the value of the first item in the DDL. I was told to add the !IsPostBack in the page load,but it didn't help.
Codes:
protected void Page_Load(object sender, EventArgs e)
{
string testeddl;
codProfessor = Request.QueryString["id"];
if (db.conecta())
{
ddlTeste.Items.Clear();
ddlTesteAltDel.Items.Clear();
ddlQuestoes.Items.Clear();
listaX = db.retornaTestes(codProfessor);
for (int i = 0; i < listaX.Count; i++)
{
testeddl = listaX[i].nometeste;
ddlTesteAltDel.Items.Add(testeddl);
}
protected void btnBuscarTeste_Click(object sender, EventArgs e)
{
if (db.conecta())
{
int posic = ddlTesteAltDel.SelectedIndex;
txtNomeTeste.Text = listaX[posic].nometeste;
ddlaltdelTeste.Text = listaX[posic].materiateste;
}
}
}
}
In Page_Load, just need to indicate:
if(!IsPostBack()
{
// rest of the code.
}

Capture a value from a dropdownlist where the display dropdownlist is not default

I want to capture the selected date on my DropDown list, where there are five days will display on DropdownList.
I'm usually putting the default value on DropDown, but not this time because in the drop down list I want it always display the current date and the next five days. But I don't know how to capture the data.
<asp:DropDownList ID="ddldate" runat="server">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(
DateTime.Now.AddDays(i).ToShortDateString(),
DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
You're repopulating the DropDownList for every postback and reloading the page, hence the SelectedValue property value may be different from the posted value. Just put a check against IsPostBack to prevent repopulating DropDownList data on postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
You should not bind data on PostBack, change your FormLoad code to below sample:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
If you check the PostBack property as condition, your SelectedValue will keep, otherwise DropDown will bind on each page-post.
And I also recommend you to check SelectedValue status before use it, don't try to get value if this null, check the following code:
protected void Button1_Click(object sender, EventArgs e)
{
if(ddldate.SelectedValue != null)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
}

Total Row Count SqlDataSource GridView

So I have a GridView set up to a SqlDataSource. Paging is enabled and I have a drop down menu that changes the number of rows displayed per page. I am able get the total of rows displayed in a single page but I want to show the total number of rows as well. (Like this: "Showing 1 - 25 of 315").
So, my questions are:
1) How do I get the total number of rows for the entire DataSource? (not just GridView) The code I have, OnSelectedData method, does not work and returns a zero.
2) How do I get the numbers to display differently for each page? For example, on the second page it needs to say "Showing 26 - 50 of 315"
Here's my code (C#):
public partial class UserControls_BloombergAllUsersControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
int gridViewTotalRowCount;
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
gridViewTotalRowCount = e.AffectedRows;
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
int pageRowsCount = GridView1.Rows.Count;
Total1.Text = "Showing 1 - " + pageRowsCount.ToString() + " of " + gridViewTotalRowCount.ToString();
}
private void BindGridView1()
{
try
{
this.GridView1.DataBind();
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
catch (Exception ex)
{ throw ex; }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView1();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridView1();
}
}
If anyone could help that would be great. Thanks!
you could set paging information to Total1 text in onSelectedData handler as the following
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
int startRowOnPage = (GridView1.PageIndex * GridView1.PageSize) + 1;
int lastRowOnPage = startRowOnPage + GridView1.Rows.Count - 1;
int totalRows = e.AffectedRows;
Total1.Text = "Showing " + startRowOnPage.ToString() +
" - " + lastRowOnPage + " of " + totalRows;
}
So you SQLDataSource should be like this sample:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
OnSelected="onSelectedData"
... >
</asp:SqlDataSource>
And you don't need to do anything for paging information in GridView1_DataBound.
I mean you could remove OnDataBound="GridView1_DataBound" out from your GridView declaration.
EDITED
To set the PageSize, you should set a default value for it such as the following sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
}
Since you are using SqlDataSource, try this code:
Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEvent Args) Handles
SqlDataSource1.Selected
Dim cnt As Integer = e.AffectedRows
End Sub

Why can I not catch the value of Gridview row?

Here is my code.
problem: When click om a row och on select the page is refreshing and i dont get the text in the lable17.text.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Label17.Text = row.Cells[2].Text.ToString() ;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.cursor='Pointer';this.style.backgroundColor='Yellow'");
}
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewSelectedIndex];
Label17.Text = "you selected" + row.Cells[2].Text;
}
Is your GridView in an UpdatePanel? If not the entire Page will postback when you click on the Button. Also, make sure that if you are setting the Text of Label17 in the Page_Load event that you only do it the first time i.e.
public void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label17.Text = "Default Text";
}
}

Problems highlighting DataList

I have written this code, but the attribute is failed to be added to the markup. what is the problem? thanks
protected void Page_Load(object sender, EventArgs e)
{
PycDBDataContext db = new PycDBDataContext();
IEnumerable<seller_profile> profs = from rows in db.seller_profiles select rows;
ProfilesView.DataSource = profs;
ProfilesView.ItemCreated += new DataListItemEventHandler(ProfilesView_ItemCreated);
ProfilesView.DataBind();
}
void ProfilesView_ItemCreated(object sender, DataListItemEventArgs e)
{
e.Item.Attributes.Add("OnMouseOver", "this.style.backgroundColor = 'lightblue';");
}
What you really want is the ItemDataBound event and not the ItemCreated event.
Rewrite like this and you would be fine.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataList ProfilesView;
PycDBDataContext db = new PycDBDataContext();
IEnumerable<seller_profile> profs = from rows in db.seller_profiles select rows;
ProfilesView.DataSource = profs;
ProfilesView.ItemDataBound += new DataListItemEventHandler(ProfilesView_ItemDataBound);
ProfilesView.DataBind();
}
}
private void ProfilesView_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor = 'lightblue';");
e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor = 'white';");
}
}

Categories

Resources