I have a gridview, which gets info by parametrized sqldatasource. I want to fire up a function by pressing a button, sending one of the fields (id).
But function won't even fire up..
here's my aspx part:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:igroup20_test2ConnectionString %>"
SelectCommand="select mie.e_num, mie.id, m.f_name, m.l_name from memberInEvent mie, member m where e_num=#num and mie.id=m.id" >
<SelectParameters>
<asp:Parameter DefaultValue="066643776" Name="num" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:PlaceHolder ID="head_line_ph" runat="server"></asp:PlaceHolder>
<br /><br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
here's my code behind:
protected void Page_Load(object sender, EventArgs e)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
protected void remove_member(object sender, EventArgs e)
{
string mem_id = ((Button)sender).CommandArgument;
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
EDIT:
after reading Suhani Mody's answer I changed it to fire on the gridview's rowcommand like that: (but still doesn't fire up)
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' CommandName="MyRowButton" runat="server" Text="הסר מאירוע" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyRowButton")
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
}
Put the All code of page load in IsPostBack Block.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
If your control (button) is inside a row of a gridview,its event will not fire like how it does for normal buttons. This is called event bubbling. If your controls are inside a container, they become a child of that container.
e.g. in your case, button is a child for gridview and in that case, child cannot fire their events directly. They will send their event to their container/parent i.e. gridview in your case and you need to deal with an event of that parent i.e. gridview.
Try to use OnRowCommand event of your gridview. That should help. You can use "FindControl" method to find your button control on that row.
Hope this helps! Let me know if you need further help.
I think this is your button
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Change it to :
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Eval("id") %>' runat="server" Text="הסר מאירוע" CommandName="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Now in gridviews rowcomand event
protectected void Gv_RowCommand(object sender, GridRowCommandEventArgs e)
{
if(e.CommandName.Equals("remove_member"))
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
}
System.Thread.Sleep(500); // To hold the current thread for few second to complete the operation and then redirect to your desired page
Response.Redirect("memberInevents.aspx?enum=" + num);
}
See Here
Your old code.
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
New Code:
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
Problem:
Binding must be inside !Ispostback
Related
I have a status column which includes approved, rejected or cancelled. I have another Actions column which contain link buttons approve and reject. Now if the status is Cancelled, I want the link button to be disabled for that row.
I tried to use GridView1_DataBound event but couldn't figure out the logic.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Server.HtmlDecode(e.Row.Cells[0].Text.Trim()).Equals("Cancelled"))
{
//OR you can disable it instead of complately hiding it
((LinkButton)GridView1.Rows[e.Row.RowIndex].Cells[0].Controls[0]).Enabled = false;
}
}
}
Method A
The following should work:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton runat="server" Enabled='<%# !(Eval("Status").ToString().Equals("Cancelled")) %>'>Approve</asp:LinkButton>
<asp:LinkButton runat="server" Enabled='<%# !(Eval("Status").ToString().Equals("Cancelled")) %>'>Reject</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Method B
Nevertheless, if you do insist on the code-behind approach the safest way to access the LinkButton controls is the following:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Status" DataField="Status" />
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="ApproveButton" runat="server">Approve</asp:LinkButton>
<asp:LinkButton ID="RejectButton" runat="server">Reject</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text.Equals("Cancelled"))
{
((LinkButton)e.Row.FindControl("ApproveButton")).Enabled = false;
((LinkButton)e.Row.FindControl("RejectButton")).Enabled = false;
}
}
}
Explanation
Your code doesn't work because the LinkButton controls are not placed in the cell's Controls collection in the way you're expecting them to. Find out yourself by placing a breakpoint inside the inner condition of GridView1_RowDataBound and check out the items of the Controls collection. You'd be surprised!
Maybe you can use this code
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="gridView_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Column1" DataField="Column1" />
<asp:BoundField HeaderText="Column2" DataField="Column2" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%#Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="lnkAction" runat="server">Approve</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var status = (e.Row.FindControl("lblStatus") as Label).Text;
if (status == "Cancelled")
{
(e.Row.FindControl("lnkAction") as LinkButton).DisableControl("Disabled button.");
}
}
}
And to disable the button you can use an extension method
public static class Extensions
{
public static TControl DisableControl<TControl>(this TControl control, string desableMessage) where TControl : WebControl
{
control.Attributes.Add("disabled", "");
control.Attributes.Add("data-toggle", "tooltip");
control.Attributes.Add("title", disableMessage);
control.Enabled = false;
return control;
}
}
I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}
This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}
I am using html to create a datagrid and in the syntax for the grid, I have CausesValidation="True" BUT I still get the dreaded
Invalid Postback
This is the code behind and if additional info is needed please let me know as I am pulling my hair out to resolve this issue.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Setup();
GetThing1();
GetThing2();
}
}
private void GetThing1()
{
this.gridInfo.Visible = true;
//Run SQL Query to populate datagrid
this.gridInfo.DataSource = DS;
this.gridInfo.DataBind();
}
protected void gridInfo_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (!Page.IsPostBack)
{
if (e.CommandName == "AlterData")
{
Response.Redirect(".../pages/newpage.aspx");
}
}
}
private void GetThing2()
{
if (userNameType == "Valid")
{
//Run this SQL Procedure
//bind to datagrid
}
else
{
//Run this procedure
//bind to datagrid
}
}
And this is the HTML/CSS used for creating the grid itself
<asp:DataGrid runat="server" ID="gridInfo" AutoGenerateColumns="false" CssClass="DataGrids"
GridLines="Both" ShowFooter="true" OnItemCommand="gridInfo_ItemCommand" OnItemDataBound="gridInfo_ItemDataBound">
<ItemStyle CssClass="row" />
<FooterStyle CssClass="DataGridFooters" />
<HeaderStyle CssClass="DataGridHeaders" />
<Columns>
<asp:TemplateColumn HeaderText="ID" ItemStyle-CssClass="Blue" ItemStyle-HorizontalAlign="Center"
HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="40" Visible="true">
<ItemTemplate>
<asp:LinkButton ForeColor="White" ID="btnEdit" runat="server" CausesValidation="True"
CssClass="BoldTextWhite" CommandName="Edit" Text='<%# Eval("ID") %>' CommandArgument='<%# Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="ID" HeaderText="ID" Visible="false"> </asp:BoundColumn>
<asp:BoundColumn DataField="first name" HeaderText="First"></asp:BoundColumn>
<asp:BoundColumn DataField="last name" HeaderText="Last"></asp:BoundColumn>
</asp:TemplateColumn>
Setup method below....
private void Setup()
{
this.lblMessage.Text = "Please click an ID from the grid for further information";
}
And this message is thrown when I click one of the ids in gridinfo, which should launch a seperate page, not load any data to the grid so I am not sure why this error is displaying.
Need more information, what exactly you are doing when you get this error. Also there is no code for your Setup() method. How is the postback event is fired, have you click on any control on the page?
I'm having problems with my ASP.NET Web application:
I have a Gridview that shows the rows of the "Pages" table on a mdb database; next to the id and the titles are two buttons, Edit and Delete. While the edit button works perfectly, the delete one won't work. I've put breakpoints at the beginning of the delPagina (delete page) method and it seems that such method does not run at all. This is the Gridview Code:
<asp:GridView ID="grdPagine" CssClass="table table-condensed" BackImageURL="../media/img/hbg.png" runat="server" AutoGenerateColumns="false" OnRowDeleting="delPagina">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="titolo" HeaderText="Titolo" />
<asp:TemplateField>
<ItemTemplate>
Modifica
<asp:Button ID="delBut" runat="server" CssClass="btn btn-danger" CommandName="Delete" Text="Elimina" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the delPagina method:
public int delPagina(int _id)
{
Data.DB.OleDbDatabase db = new Data.DB.OleDbDatabase();
string query = "DELETE FROM pagine WHERE id="+ _id;
return db.EseguiNonQuery(query);
}
The Event:
protected void delPagina(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(this.grdPagine.Rows[e.RowIndex].Cells[0].Text);
int b = new PaginaService().delPagina(id);
List<Pagina> pag = new PaginaService().mlistapagine();
this.grdPagine.DataSource = pag;
this.grdPagine.DataBind();
}
Sorry if my terminology is a bit off but this is kind of a new word for me.
Thanks in advance
Edit: When i click on the button there is a page refresh but no gridview is shown, so i have to refresh again manually.
You can use RowCommand and CommandArgument, Please look to following code sample
<asp:GridView ID="grdPagine" CssClass="table table-condensed" BackImageURL="../media/img/hbg.png" runat="server" AutoGenerateColumns="false" OnRowCommand=grdPagine_RowCommand" OnRowDeleting="delPagina">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="titolo" HeaderText="Titolo" />
<asp:TemplateField>
<ItemTemplate>
Modifica
<asp:Button ID="delBut" runat="server" CssClass="btn btn-danger" CommandName="Delete" Text="Elimina" CommandArgument='<%# Bind("id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in code behind declare
protected void grdPagine_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
int b = new PaginaService().delPagina(id);
List<Pagina> pag = new PaginaService().mlistapagine();
this.grdPagine.DataSource = pag;
this.grdPagine.DataBind();
}
}
Hopefully the above code solves your problem
According to your code there is no click event in delBut button
you can use RowCommand event in gridview since your buttons CommandName="Delete"