I am trying to delete data from a gridview using a a link button. I need help with the logic and making the link button remove the row data from the database on click.
GridView
<asp:GridView Style="width: 100%" ID="GvReportResults" runat="server" AutoGenerateColumns="False" EmptyDataText="No data" ShowHeaderWhenEmpty="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkBtnEdit" runat="server" CausesValidation="false" >Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LnkBtnRemove" runat="server" CausesValidation="false" CommandName="DeleteItem" CommandArgument='<%# Eval("OtherDataID") %>'>Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SourceID" HeaderText="ID" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="MiddleName" HeaderText="Middle Name" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="NationalID" HeaderText="SSN" />
<asp:BoundField DataField="DOB" HeaderText="DOB" />
<asp:BoundField DataField="HireDate" HeaderText="Hire Date" />
<asp:BoundField DataField="Address1" HeaderText="Address" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="State" HeaderText="State" />
<asp:BoundField DataField="PostalCode" HeaderText="Zip Code" />
</Columns>
</asp:GridView>
Store precedure thats importing data to gridview
private void BindGrid()
{
//set up arguments for the stored proc
int? FacilityID = (ddlFacility2.SelectedValue.Equals("-1")) ? (int?)null : int.Parse(ddlFacility2.SelectedValue);
int? OtherDataID = null;
//bind
GvReportResults.DataSource = this.DataLayer.model.MS_spGetOtherData(FacilityID, OtherDataID);
GvReportResults.DataBind();
}
Add OnClick attribute for the LinkButton, for example (added OnClick to your linkbutton code)
<asp:LinkButton ID="LnkBtnRemove" runat="server" CausesValidation="false" CommandName="DeleteItem" CommandArgument='<%# Eval("OtherDataID") %>' OnClick='LnkBtnRemove_Click'>Delete</asp:LinkButton>
Have OnClick listener as
protected void LnkBtnRemove_Click(object sender,EventArgs e)
{
string id = ((LinkButton)sender).CommandArgument;//CommandArgument is always returns string
Do_DeleteRow(id);//method to delete
BindGrid();
}
private void Do_DeleteRow(string id)
{
//your delete code will be added here
}
Just attach ItemCommand event to your grid
On web page in your grid definition add:
<asp:DataGrid OnItemCommand="Grid_ItemCommand" />
after that in code behind:
void Grid_ItemCommand(Object sender, DataGridCommandEventArgs e)
{
var id = Int32.Parse(e.CommandArgument.ToString()); //use parse if OtherDataID is int
//here goes logic for deleting row
this.DataLayer.model.spDeleteData(id);
//after deleting rebind grid
BindGrid();
}
Convert your boundfiled into Item Template, Here using sourceid will fire delete Query.
Code look like this:
protected void GvReportResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteItem")
{
int getrow = Convert.ToInt32(e.CommandArgument);
Label lblSourceID = (Label)GvReportResults.Rows[getrow].FindControl("lblSourceID");
bool flag=deleteRecord(lblSourceID.text);
if(flag)
{
succes msg!
}
else{ failed msg}
}
}
public bool deleteRecord(String SourceID)
{
try
{
SqlCommand cmd = new SqlCommand("Your Delete Query where condtion ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
return true;
}
catch(Exception ac)
{
return false;
}
}
Related
I have this GridView that fills on the Page_Load:
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
GridView1.DataSource = actBO.BuscarActividades();
GridView1.DataBind();
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
<asp:BoundField DataField="Class" HeaderText="Class" />
<asp:BoundField DataField="Day" HeaderText="Day" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:BoundField DataField="Vacants" HeaderText="Vacants" />
<asp:ButtonField ButtonType="Button" HeaderText="Book" Text="Book"/>
</Columns>
</asp:GridView>
Where column "Vacants" shows an int (it represents the amount of vacant booking spaces in a class).
Every row will have a button to book a specific class. I need to place a condition for when the field "Vacants" is zero, so the "Book" button will be disabled.
So far this is what it looks like: image.
As you can see, I need the button to be disabled when there are no more vacants. It shouldn't be able to be clicked.
To do so, you must register OnRowDataBound event. More explanations can be found in here.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
<asp:BoundField DataField="Class" HeaderText="Class" />
<asp:BoundField DataField="Day" HeaderText="Day" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:BoundField DataField="Vacants" HeaderText="Vacants" />
<asp:ButtonField ButtonType="Button" HeaderText="Book" Text="Book"/>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get your button via the column index; ideally you could use template field and put your own button inside
var button = e.Row.Cell[5].Controls[0] as Button;
int vacant = 0;
var vacantVal = int.TryParse(e.Row.Cell[4].Text, out vacant);
if (button != null)
{
button.Enabled = vacant > 0;
}
}
}
Hope it helps.
I have a Gridview which also contains a button field. When this button on a particular row is clicked, I want it to update my database. For example, if a row contains (SN = 1) I want it to update the button to update the database with the row that contains "SN = 1". How do I get the SN of the row when the button on that same row is clicked?
This is my Gridview definition:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>
Here, when the row button is clicked, I want to update my database with the signout time. I can't seem to get it to get the SN of the row and update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
}
}
If the value you seek is the comes from the same datasource, you can add the value as a CommandArgument:
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out"
runat="server"
Text="Sign out"
CommandName="SignOut"
CommandArgument='<%# Eval("SN") %>'/>
</ItemTemplate>
</asp:TemplateField>
On your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
string sn = e.CommandArgument.ToString();
if (sn == "1")
{
/*DO STUFF....*/
}
}
}
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
I have a GridView that contains a CheckBox control. Once the users check the rows that they want, they click a button and I have to update the database for each checked row.
I have the code to iterate trough the gridview rows and look at the checkbox value, but its always false, even if its checked. I do get a reference to the checkbox in ignore but it is always false. What am I missing here?
aspx.cs file:
protected void Ignore_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdNotReceived.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ignore = (CheckBox)row.FindControl("chkIgnore");
if (ignore.Checked)
{
// Update Database
}
}
}
}
.aspx page:
<asp:GridView ID="grdNotReceived" runat="server"
Width="600px"
CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
PagerStyle-CssClass="pgr" AutoGenerateColumns="false">
<AlternatingRowStyle CssClass="alt"/>
<Columns>
<asp:BoundField DataField="Store" HeaderText="Store" />
<asp:BoundField DataField="Dept" HeaderText="Dept" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="RefNumber" HeaderText="RefNumber" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Vendor" HeaderText="Vendor" />
<asp:BoundField DataField="Total" HeaderText="Total" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView databind method:
protected void LoadExceptions()
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
If your databinding function ( LoadExceptions() ) is being called somwhere on the page load (like the Load event or class constructor) then it's overriding the changes the user has made in the form.
Don't databind if the page is in post back, you can add an if (!Page.IsPostBack) before calling LoadExceptions() or you can update LoadExceptions() to check it:
protected void LoadExceptions()
{
if (!Page.IsPostBack)
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
}
I have a gridview with a template field. In that template field is a checkbox. I have a submit button outside of the gridview to assign the records that were checked. On the postback no checkboxes register as being checked. Here is my Code:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cb" Checked="false" runat="server" />
<asp:Label ID="lblCFID" runat="server" Visible="false" Text='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="Name" HeaderText="Name" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="DOB" HeaderText="Date of Birth" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Gender" DataField="Gender" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Status" DataField="Status" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Plan Name" DataField="PlanName" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Type" DataField="ControlType" />
<asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Date of Service" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" DataField="DateofService" />
</Columns>
protected void AssignRecords(object sender, EventArgs e)
{
int Rows = gvASH.Rows.Count;
for (int i = 0; i < Rows; i++)
{
//CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
CheckBox cb = (CheckBox)gvASH.Rows[i].Cells[0].FindControl("cb");
Label lblID = (Label)gvASH.Rows[i].Cells[0].FindControl("lblCFID");
if (cb.Checked == true)
{
string ID = lblID.Text;
//Assign Code
}
}
}
I have a breakpoint set on the string ID = lblID.Text; but it never finds any that are checked.
I think what you are missing is, when you click on the button and your page is postback, you rebinding to gridview, you need to bind in this condition like
if (!Page.IsPostBack)
{
GridView1.DataSourceID = "yourDatasourceID";
GridView1.DataBind();
}
On a postback, the contents of the GridView are re-created from the postback Viewstate data between page_init and page_load. Perhaps try examining your Gridview in page_load to see what's there.
set the autopostback attribute of Checkbox
AutoPostBack="true"