Delete Selected Dynamic Checkboxes on Gridview ASP.NET - c#

I have a gridview that contains data from a database. I have dynamically created checkboxes for each row. What I want is when I click the "delete selected" button, the checkboxes that are checked will be deleted. But the rows don't get deleted when I click the button. Here is the code for the button:
protected void btnDeleteSelectedServiceProvidersLocations_Click(object sender, EventArgs e)
{
int x = 102;
string delete;
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
delete = Request.Form["gvServiceProviders$ct" + x + "$cbSelect"];
if (delete != null || delete == "on" || delete == "y")
{
bll.ServiceProviderLocationID = grow.Cells[1].Text;
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
x++;
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
}
The gridview is inside an update panel, if that helps. And I'm using a three-tier approach.
ASPX code:
<div ID="gridView">
<asp:GridView ID="gvServiceProviders" runat="server">
<Columns>
<asp:templatefield HeaderText="Select">
<itemtemplate>
<asp:CheckBox ID="cbSelect" runat="server"/>
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
</div>

You want to delete the data when the check box is selected then you can do as below,
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
//Make sure it is datarow
if(grow.RowType = RowType.DataControlRowType.DataRow)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)grow.FindControl("cbSelect");
//Make sure if checkbox is selected for the processing row
if(chkdelete.Checked)
{
//Getting your datakey value
bll.ServiceProviderLocationID = Convert.ToInt32(gvServiceProviders.DataKeys[grow.RowIndex].Value);
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
}
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
As this is using the datakey of the gridview you need to set the DataKey property of the gridview with the LocationID.

Try this code:
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in gvDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
using (SqlConnection con = new SqlConnection("Data Source=Test;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}

Related

Passing of data from gridview to a new page

It is something very simple but i am stuck on this for ages.
So i had created a datatable and got the data onto a gridview. Great
Made the Sheet_id clickable and when clicking it i will direct to a new page.
However i want to get the sheet_id which i selected from the gridview in order to use it for other sql query.
How do i pass that sheet_id from one page to another page using the linkbutton.
This is ExistingSheet.aspx
<asp:GridView ID="grdSheet" runat="server" AutoGenerateColumns="False"
CssClass="tablesorter table table-bordered table-hover table-striped tblCtr"
>
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="hdnSheetId" runat="server" Text='<%# Eval("SNO")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sheet ID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="sheetId" CommandName="sheet_id" CommandArgument='<%# Eval( "sheet_id")%>' Text='<%# Eval( "sheet_id")%>' OnClick="" PostBackUrl="~/SheetDetail.aspx">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
This is ExistingSheet.aspx.cs
protected void grdSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("SheetDetail.aspx" + e.CommandArgument);
}
This is the page i wanted to get the data to SheetDetail.aspx.cs
public void FillGridSheet()
{
eExistingSheetQuery existingSheetQuery = new eExistingSheetQuery();
grdSheetDetail.DataSource = existingSheetQuery.DisplayReportSheet(**SHEET ID TO BE PLACED HERE**);
grdSheetDetail.DataBind();
}
This is eExistingSheetQuery.cs
public DataTable DisplayReportSheet(string sheetId)
{
try
{
conn = new SqlConnection(estocktake);
conn.Open();
DataTable dtd = new DataTable();
GridView gvd = new GridView();
cmds = new SqlCommand("Select ROW_NUMBER( ) OVER (order by sheet_id) as SNO, csd.Barcode, csd.ItemId, pm.Description, csd.Quantity " +
"from CountSheetDetails csd " +
"join ProductMaster pm on pm.Barcode = csd.Barcode and pm.ItemId = csd.ItemId " +
"where csd.SheetId = '" + sheetId + "' and pm.Status ='A';",conn);
adpt = new SqlDataAdapter();
adpt.SelectCommand = cmds;
cmds.ExecuteNonQuery();
adpt.Fill(dtd);
conn.Close();
conn.Dispose();
for (int i = 0; i < dtd.Rows.Count; i++)
{
dtd.Rows[i]["SNO"] = i + 1;
}
return dtd;
}
catch (Exception)
{
conn.Close();
conn.Dispose();
return null;
}
}
i wanted to use the id to beable to use it for the next query that i am going to pull from SQL
I had seen a few example but i do not think i really understand. Any suggestion will be great. thanks!
I think what you're asking is a way to pass data from one GridView to another, but on a different page?
Using a loop mechanism, I suggest you loop through your source Gridview and copy them into your destination GridView. Get this to work first on a single page first - ie GridView to GridView.
For example, you'll need a trigger. Here's a Button trigger to get the data ...
GridView1 = your source GridView
GridView2 = your destination GridView
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ColumnName1"));
dt.Columns.Add(new DataColumn("ColumnName2"));
dt.Columns.Add(new DataColumn("ColumnName3"));
foreach (GridViewRow gvr in GridView1.Rows)
{
if (((CheckBox)gvr.Cells[4].FindControl("CheckBox")).Checked == true)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
}
foreach (GridViewRow gvr in GridView2.Rows)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
GridView2.DataSource = dt;
GridView2.DataBind();
}
Once you get this to work, your way, then we figure out how to pass the data across different web URLs.
One approach is to use SessionState[]. Here.
The concept is basically about passing data into memory, which is the SessionState or ViewState, and then retrieving that data from the receiving page via it's PageLoad() event. OR you save the data into a temporary table, and reload it again onto the new page, using standard DataSource attributes.
Examples here and here.

Display DropDownlist when click on specific cell asp.net table

I am trying to figure it out how can I display a dropDownList on a specific cell in the table right after clicking a button "Show DropDownlist" located on that cell.
This is the behind code , right now it is displaying the dropDownList at the last cell of each row. and I want to make it appear only when a button is clicked.
while (rdr.Read())
{
TableRow tRow = new TableRow();
myTable.Rows.Add(tRow);
for (int i = 0; i <= 4; i++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
if (i == 4)
{
tCell.Controls.Add(SM_List()); //Adding the dropdownlist
tRow.Cells.Add(tCell);
continue;
}
tCell.Text = rdr.GetString(i);
tCell.Attributes.Add("onmouseover", "this.style.cursor = 'pointer'; this.style.backgroundImage = ''; ");
tCell.Attributes.Add("onClick", "getData()");
tRow.Cells.Add(tCell);
}
/* iterate once per row */
}
I want to add this code, so it will be a button at first , instead of a drop down list :
Button bt = new Button();
bt.Text = "Switch";
bt.Click += new EventHandler(DropDownList_Show);
tCell.Controls.Add(bt);
But I am not sure how to display the DropDownList at the exact cell the button was located. and also I want to do some actions when Value was selected in the dropdownlist.
Can you please assist , I feel a little bit lost.
You can solve this issue easily by using GridView in ASP.NET.
Let say the GridView is declared as following in ASPX page.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" />
<asp:BoundField DataField="Token" />
<asp:BoundField DataField="Secret" />
<asp:ButtonField CommandName="ShowDropDown" Text="Show" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropDownList" runat="server" Visible="false">
<asp:ListItem Text="Valid" Value ="1"></asp:ListItem>
<asp:ListItem Text="Invalie" Value ="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Following is the method in code behind which populates the GridView.
private void BindGridView()
{
var tokens = new List<AccessToken>();
using (var conn = new SqlConnection("Server=somedbserver;Database=somedatabase;User Id=someuser;Password=somepassword;"))
{
using (var command = new SqlCommand())
{
command.Connection = conn;
command.CommandText = "SELECT Id, Token, Secret FROM Tokens";
command.CommandType = System.Data.CommandType.Text;
conn.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var token = new AccessToken();
token.Id = reader.GetInt32(0);
token.Token = reader.GetString(1);
token.Secret = reader.GetString(2);
tokens.Add(token);
}
}
}
}
GridView1.DataSource = tokens;
GridView1.DataBind();
}
And I am calling this method in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridView();
}
}
Following is the event handler of RowCommand event of GridView which will display the dropdown list in the column next to the button which is clicked.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "ShowDropDown")
{
var row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
//Using Cell[4] coz the Dropdownlist is in 5th column of the row.
//You need to replace 4 with appropriate column index here.
//Also replace "dropDownList" with the ID assigned to the dropdown list in ASPX.
var ddl = (DropDownList)row.Cells[4].FindControl("dropDownList");
if(ddl != null)
{
ddl.Visible = true;
}
}
}
You will able resolve your issue if you follow this approach.

Populated GridView is empty when I attempt to iterate through the rows

I have a GridView that I populate. It appears correctly and shows the data. It contains a Checkbox column, and my intent is when the user clicks a button on the form, it iterates through the rows of the GridView, and totals up all the rows the user has selected by checking the CheckBox.
(I got the details of how to do this from http://asp.net-informations.com/gridview/checkbox.htm)
The problem comes at this point, and I've discovered that just before it gets to the line
foreach (GridViewRow row in grdItems.Rows)
grdItems.Rows.Count = 0, even though the GridView is currently displaying data.
The GridView:
<asp:GridView ID="grdItems" AutoGenerateColumns="false" runat="server" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Item_No" HeaderText="Item No" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
</Columns>
</asp:GridView>
The Button:
<asp:Button ID="cmdOK" runat="server" Text="Add" />
The Button Onclick:
protected void cmdOK_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SaveP2P();
}
}
The method the populates the GridView:
private void FillGrid()
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Snipped for privacy");
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandText = "Snipped for privacy";
cmd.Connection = conn;
System.Data.OleDb.OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter(cmd);
System.Data.DataSet ds = new System.Data.DataSet();
adp.Fill(ds);
adp.Dispose();
cmd.Dispose();
conn.Close();
grdItems.DataSource = ds;
grdItems.DataBind();
}
The ValidateForm() method which contains the code I'm struggling with
private bool ValidateForm()
{
bool result = true;
decimal TotalAmount = 0;
//If I display a message here, it shows grdItems.Rows.Count is 0
foreach (GridViewRow row in grdItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
TotalAmount += Decimal.Parse(row.Cells[2].Text);
}
}
}
decimal amount;
if (decimal.TryParse(txtAmount.Text, out amount))
{
if (amount > TotalAmount)
{
result = false;
}
}
else
{
result = false;
}
return result;
}
This sounds like a viewstate issue where when the page is posting back to the server, it is losing all the data in the grid. Have you tried enabling viewstate on your page to see if the gridview rows are returned.

How to disable a link button in gridview when clicked

I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveRow")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
lnkbtn.Enabled = false;
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int TimeSheetId = Convert.ToInt32(e.CommandArgument);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetId", TimeSheetId);
con.Open();
cmd.ExecuteNonQuery();
GetManagerTimeSheets();
}
}
}
Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];
You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}

How add control programmatically in gridview template?

I want add control label in my gridview, is it possible add with datatable?
here my code:
<asp:GridView ID="reportScheduleDetailsGridView"
runat="server"
AutoGenerateColumns="False">
</asp:GridView>
I try use tag html span, but it not render:
string queryString = #"SELECT * FROM [table1]";
SqlCommand cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrMaster = cmd.ExecuteReader())
{
while (sdrMaster.Read())
{
DataRow rows = dataTable.NewRow();
rows[0] = sdrMaster["name"].ToString();
for (var x = 1; x < maxCol; x++)
{
queryString = #"SELECT * FROM table2";
cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrRev = cmd.ExecuteReader())
{
while (sdrRev.Read())
{
blok = "<span></span>";
no = (int)Int16.Parse(sdrRev["no"].ToString());
}
}
rows[x] = blok;
if (no > 1)
{
no--;
}
else
{
blok = "";
}
}
dataTable.Rows.Add(rows);
} }
I don't know, how can add control asp in gridview, like label.
Please help, thanks.
One way to add controls is using OnRowDataBound event of GridView. Add a placeHolder to say, inside <ItemTemplate> of your grid view.
<asp:GridView ID="EmpGridView" OnRowDataBound="EmpGridView_RowDataBound"
<ItemTemplate>
<asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
...></asp:GridView>
Ang your code behind file will have:
protected void EmpGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Create a label control
Label lbl = new Label();
lbl.Text="MyDynamic Label";
lbl.ID="lbl1"; // use ID values you prefer
// lets create one more control for example
LinkButton btnlink = new LinkButton();
btnlink.Text = "Delete";
btnlink.ID = "btnDelete";
linkb.Click += new EventHandler(btnlink_Click);
// add the controls to your placeholder inside <ItemTemplate>
PlaceHolder phld = e.Row.FindControl("Placeholder1") as PlaceHolder;
phld.Controls.Add(btnlink);
phld.Controls.Add(lbl);
//code to add the control to only a specific COLUMN/ Cell
e.Row.Cells[1].Controls.Add(btnlink); // adding to 2nd Column
// adding to last column..
e.Row.Cells[EmpGridView.Columns.Count - 1].Controls.Add(btnlink);
}
}
Hope this various ways of adding controls to Templates as well as in a cell of GridView helps you.

Categories

Resources