set checkbox in gridview based on datatable value - c#

I have a gridview control with a checkbox field and several bound fields. The checkbox field does not directly map to a field in the database. Rather, i want to read a value from a field in the database and "check" some of the checkboxes.
For example, given the following data from the database -> datatable
PROCESSED NAME DATE
Y Mickey Mouse 11/15/2011
N Donald Duck 4/01/2012
Y James Bond 5/02/2011
I would like the gridview to display a checkbox and set the value of boxes to UNCHECKED where PROCESSED = N and for PROCESSED = Y either have an uneditable checkbox or no checkbox at all.
PROCESSED NAME DATE
[/] Mickey Mouse 11/15/2011
[ ] Donald Duck 4/01/2012
[/] James Bond 5/02/2011
To populate the gridview, a SQL stmt is run against a database, and the result of the SQL query is stored in a datatable. Before binding the datatable to the gridview, i would like to check the "processed" field and set the checkbox based on that value.
Here is the gridview control (shortened for clarity):
<asp:GridView ID="gridview_all_applicants" runat="server" AllowPaging="True">
<Columns>
<asp:TemplateField HeaderText="Complete">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="lastname" HeaderText="Last Name" ReadOnly="True" SortExpression="lastname" />
Here is what i have so far in the code behind
SqlCommand cmd = new SqlCommand(sql query here);
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
// do some processing of data returned from query
// read the char value from the returned data and set checkbox
procflag = r["process_flag"].ToString().ToLower();
CheckBox chkbox = new CheckBox();
if (procflag == null || procflag == "n")
{
// SET CHECKBOX TO "NOT CHECKED"
}
else
{
// SET CHECKBOX TO "CHECKED" AND MAKE IT UNCLICKABLE
// ----OR---- DO NOT DISPLAY CHECKBOX AT ALL.
}
} // end for each
gridview_all_applicants.DataSource = dt;
gridview_all_applicants.DataBind();
any help is greatly appreciated.

You can do it like this:
First in sql server:
SELECT
CAST(CASE PROCESSED WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED
NAME
DATE
FROM ExampleTable
in c# code:
SqlCommand cmd = new SqlCommand(sql query here);
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
gridview_all_applicants.DataSource = dt;
gridview_all_applicants.DataBind();
and finally in aspx:
<asp:TemplateField HeaderText="Complete">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server" Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>' Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'/>
</ItemTemplate>

How about a database agnostic solution, just on the off chance you are using a non sqlserver database ;)
<asp:CheckBox ID="process_flag_check" runat="server"
Checked='<%# Eval("process_flag").ToString() == "Y" ? "True": "False" %>'
Enabled="false"/>
</asp:Content>

<asp:CheckBox ID="process_flag_check" runat="server"
Checked='<%# bool.Parse(Eval("process_flag").ToString() == "Y" ? "True": "False") %>'
Enabled="false"/>
</asp:CheckBox>
This one Perfectly Works.I have modified using Kevin and marco Code.
Thank u Kevinv and Marco

Related

If date column (column A) in gridview is today's date, show expired in column B

I have a gridview that is getting data from a stored procedure. Column A is a date field. Column B has the text active (for all rows). However, I would like to change the text of 'active' (in the status column) to 'expired' based on the date - so if it's today's date or older, show expired. I know I could execute a job on the SQL server to change the column before importing into my table. However, I would like to only change the text and not alter the DB if possible. So, how would I manipulate the active column to show expired based on today's date.
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
tblMytable.DataSource = dt;
tblMytable.DataBind();
con.Close();
}
The webform:
<asp:GridView ID="tblMytable" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateField" HeaderText="Date" />
<asp:BoundField DataField="Status" HeaderText="Status" />
</Columns>
</asp:GridView>
If you make it a TemplateField you have much more control over the data and you can then use a Ternary operator to apply some logic.
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("DateField")) < DateTime.Now ? "Expired" : "Active" %>
</ItemTemplate>
</asp:TemplateField>

Split a Gridview in two Grids in c#.net

I have a GridView which gets the data from a SQL Server database.
The GridView binds when the user select the date from an CalendarExtender, because the data is different one day to another, also the rows quantity.
E. G., in Saturdays the GridView is filled with 18 rows. In Tuesdays, with 58.
Concern:
What I need to do is to split the GridView in 2 parts (2 GridViews). E. G., In tuesdays, 29 rows each GridView, in saturdays, 9 rows each.
I have tried:
To bring the daily data into a GridView, called "GVTotal":
if (Weekday.Value == "Saturday")
{
GVTotal.DataSourceID = SaturdayData.ID;
GVTotal.DataBind();
}
To count the rows from GVTotal, and divide by 2.
int everything = GVTotal.Rows.Count;
int half = everything / 2;
What I want to do now, is to "Copy" the rows from 0 to half to GVPart1, and from half to everything to GVPart2, in the exactly same order than in GVTotal.
I have read that maybe using a DataTable will made this possible.
I am not pretty sure how to do that. Could someone help me please?
You could have a Repeater with two items, one for each GridView. In the example below, the Repeater is rendered as a table with a single row. Each GridView is in a cell of that row, with an empty cell between them.
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="0" cellpadding="0">
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" >
...
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 32px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
In order to get the two data sources, you declare two DataTables in your class:
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
In Page_Load, the two DataTables are populated by splitting the full DataTable in two parts, and the data source of the Repeater is set to two boolean values:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection("Data Source=(local); Integrated Security = True; Initial Catalog=TestMP"))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Clients ORDER BY ClientID ASC", conn))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
The specific data source can then be set for each GridView in the ItemDataBound event handler of the Repeater:
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bool isTopHalf = (bool)e.Item.DataItem;
GridView gvHalf = e.Item.FindControl("gvHalf") as GridView;
gvHalf.DataSource = isTopHalf ? dtTopHalf : dtBottomHalf;
gvHalf.DataBind();
}
}
Note 1: The Repeater allows to share the same markup for both GridViews. If you prefer, you can declare two separate GridViews in the markup and apply the specific data source to each one in Page_Load.
Note 2: You need a reference to System.Data.DataSetExtensions in your project to use some of the LINQ methods mentioned above.
Thanks to ConnorsFan for the assistance. His answer is the right way to do what I wanted.
As I need to select the date before the data comes in, I wrote Connor's code into my date Textbox OnTextChanged event, into the if (Weekday.Value == "<day of the week>") statement.
This is the solution:
ASPX:
Updated: Only with one GridView, as reccomended:
<asp:Repeater ID="repeater1" runat="server" OnItemDataBound="repeater1_ItemDataBound">
<HeaderTemplate>
<table cellspacing="200px" cellpadding="0">
<tr style="vertical-align: top;">
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:GridView ID="gvHalf" runat="server" BackColor="White" AutoGenerateColumns="False" HeaderStyle-CssClass="tituloshandoff" RowStyle-CssClass="contenidohandoffbatch">
<Columns>
<asp:BoundField HeaderText="IDBATCH" DataField="IDBatch" SortExpression="IDBatch" HeaderStyle-CssClass="TituloInvisible" ItemStyle-CssClass="TituloInvisible" />
<asp:BoundField HeaderText="BATCH" DataField="Nombre" SortExpression="Nombre" />
<asp:BoundField HeaderText="DEALER" DataField="DealerCodigo" SortExpression="DealerCodigo" />
<asp:BoundField HeaderText="CT TIME" DataField="CTStart" SortExpression="CTStart" />
<asp:BoundField HeaderText="STATUS" DataField="Estado" SortExpression="Estado" />
<asp:TemplateField HeaderText="CONTROL">
<ItemTemplate>
<asp:Button ID="Button1" CssClass="botongrid" runat="server" Text="Select" Width="100px" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</ItemTemplate>
<SeparatorTemplate>
<td style="width: 100px;" />
</SeparatorTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
C#:
I will show only one day in example:
string LaConexion = #"<My Connection String>";
private DataTable dtTopHalf;
private DataTable dtBottomHalf;
protected void TextDate_TextChanged(object sender, EventArgs e)
{
if (diasemana.Value == "Monday")
{
using (SqlConnection conexion = new SqlConnection(LaConexion))
using (SqlCommand comando = new SqlCommand("SELECT [1Monday].IDBatch, Batch.Nombre, Dealer.DealerCodigo, Batch.CTStart, BatchDatos.Estado FROM [1Monday] INNER JOIN Batch ON [1Monday].IDBatch = Batch.IDBatch INNER JOIN Dealer ON Batch.IDDealer = Dealer.IDDealer LEFT OUTER JOIN BatchDatos ON [1Monday].ID = BatchDatos.ID ORDER BY Batch.CTStart", conexion))
{
comando.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(comando);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
int halfCount = dt.Rows.Count / 2;
dtTopHalf = dt.AsEnumerable().Select(x => x).Take(halfCount).CopyToDataTable();
dtBottomHalf = dt.AsEnumerable().Select(x => x).Skip(halfCount).CopyToDataTable();
}
// Each value in the Repeater indicates if it is the top half or not
repeater1.DataSource = new List<bool>() { true, false };
repeater1.DataBind();
}
}
A Picture:

Store checked checkbox in gridview in database ASP.NET C#

I am able to retrieve out data from database to show which is Y and N using checkbox in gridview. However now i want to to able to store which checkbox is checked back into the database after editing.
What i did so far:
.aspx
<asp:GridView ID="SiteGridView" runat="server" CssClass="datagrid"
GridLines="Vertical" AutoGenerateColumns="False"
Width="100%"
AllowPaging="True" AllowSorting="True"
DataKeyNames="promoID" OnRowCommand="GvPage_RowCommand"
OnPageIndexChanging="GvPage_PageIndexChanging"
OnSorting="GvPage_Sorting"
OnRowDatabound="SiteGridView_RowDataBound"
OnRowEditing="SiteGridView_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Default">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server"
Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>' />
</ItemTemplate>
<ItemStyle Width="20%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
SqlCommand cmd = new SqlCommand("SELECT * , CAST(CASE defaults WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED FROM Promotions");
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
SiteGridView.DataSource = dt;
SiteGridView.DataBind();
protected void SiteGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check userrole & display accrodingly
if (Session["ROLE"].ToString() != "SA")
{
//ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnDelete");
//btnEdit.Visible = false;
SiteGridView.Columns[4].Visible = false;
}
}
}
Have you tried:
Checked='<%# Eval("PROCESSED")%>'
If so, what error messages have you gotten?
For some reason Checkboxes do not trigger GridView RowCommand events. It probably can be done with appropriate calls to ClientScript.GetPostBackEventReference(), but thats a whole other level of complexity. So, in order to act on a CheckBox click and handle events individually:
(NB: I've stripped out much of your coding to clarify my points.)
In your CheckBox set AutoPostBack="true"
Add a handler for OnCheckedChanged.
Make sure the DataKey contains the pk of the row you need to update with the CheckBox State
// Simplified version of your markup
<asp:GridView ID="SiteGridView" runat="server"
DataKeyNames="promoID"
OnRowDataBound="SiteGridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Default">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server"
Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'
OnCheckedChanged="process_flag_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the RowDataBound event, find the CheckBox and add the Row Index as an attribute
// Merge this with your `RowDataBound` event
protected void SiteGridView_RowDataBound( object sender, GridViewRowEventArgs e ) {
if ( e.Row.RowType == DataControlRowType.DataRow ) {
CheckBox cbx = ( CheckBox ) e.Row.FindControl( "CheckBox1" );
cbx.Attributes[ "data-row-idx" ] = e.Row.RowIndex.ToString();
}
}
Handle the CheckChanged event:
// Add this handler to your code
protected void process_flag_CheckedChanged( object sender, EventArgs e )
{
CheckBox cbx = ( CheckBox ) sender;
Int32 rowidx = Convert.ToInt32(cbx.Attributes["data-row-idx"]);
Int32 pk = (Int32) GridView4.DataKeys[rowidx].Value;
// simple way to see event arguments before actually touching the database
GridView4.Caption = string.Format(
"CheckChanged: Row {0}, State: {1}, RowPK: {2} ", rowidx , (cbx.Checked ? "Checked" : "Unchecked"), pk );
// Save Data and rebind the gridview to reflect changes
// Verify your parameters before attempting an actual update
// YourDatabaseCallWithAppropriateParamaters( ... );
GridView1.DataBind();
}
First of all use a foreach loop to findout which rows are checked. Then store ID of those rows in a List.
foreach (GridViewRow row in SiteGridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("process_flag") as CheckBox);
if (chkRow.Checked)
{
string ID = row.Cells[columnID].Text;

How do I send email to each user listed in the gridview individually by clicking on the sanction button?

I created a gridview on my approval.aspx page. I am using VS 2014 and SQL Server 2014.
<asp:GridView ID="gv_pending_requests" runat="server" AutoGenerateColumns="False" Width="95%" CellPadding="1" CellSpacing="2">
<Columns>
<asp:BoundField HeaderText="Requested By" DataField="username" />
<asp:BoundField HeaderText="No. of Days" DataField="total_days" />
<asp:BoundField HeaderText="Type of Leave" DataField="leave_type" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Starting" DataField="start_date"/>
<asp:BoundField HeaderText="Ending" DataField="end_date" />
<asp:TemplateField HeaderText="Sanction">
<ItemTemplate>
<asp:Button ID="btn_apprv" Text="Sanction" runat="server" OnClick="btn_apprv" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deny">
<ItemTemplate>
<asp:Button ID="btn_deny" Text="Deny" runat="server" OnClick="btn_deny"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//Now, the code from .cs file:
lbl_uid.Text = Convert.ToString(Session["Username"]);
string connectionstring = #"Data Source=server;Integrated Security=true Initial Catalog=E_M_S";
SqlDataReader rdr;
DataTable dt = new DataTable();
dt.Columns.Add("Requested By");
dt.Columns.Add("Type of Leave");
dt.Columns.Add("Reason");
dt.Columns.Add("Starting");
dt.Columns.Add("Ending");
dt.Columns.Add("No. of Days");
DataRow dr;
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
cmd.CommandType = CommandType.Text;
using (conn)
{
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
dr = dt.NewRow();
dr["Requested By"] = rdr["username"].ToString();
dr["Type of Leave"] = rdr["leave_type"].ToString();
dr["Reason"] = rdr["reason"].ToString();
dr["Starting"] = rdr["start_date"].ToString();
dr["Ending"] = rdr["end_date"].ToString();
dr["No. of Days"] = rdr["total_days"].ToString();
dt.Rows.Add(dr);
dt.AcceptChanges();
gv_pending_requests.DataSource = dt;
gv_pending_requests.DataBind();
conn.Close();
}
}
//Button for sending the E-Mail
protected void btn_apprv(object sender, EventArgs e)
{
Response.Write("<script type='javascript'>alert('The leave has been sanctioned, and mail has been sent to inform the employee of the same.');</script>");
}
Problem1 : It shows below error pointing at the line :- gv_pending_requests.DataSource = dt;
"a field or property with the name 'username' was not found on the selected data source"
Problem 2: I want that a mail be sent to each user according to the button pressed for that row. How do i define an on click event with that mail code?
Please forgive me for missing details,if any. Please help me with this error.
To your Problem 1:
In your SQL-Select-Statement you don't select for the username:
SqlCommand cmd = new SqlCommand("select leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
Instead this code should be:
SqlCommand cmd = new SqlCommand("select username,leave_type,reason,start_date,end_date from Leave where status='" + lbl_status.Text + "'", conn);
Otherwise - as stated by the errormessage - the DataReader you use cannot find the column username in the result from the database.
You can test this if you go to your database and fire the SQL-statement there directly, you will see that you do not get the usernames back.
Also, you defined your DataTable with the column Requested by.
dt.Columns.Add("Requested By");
But if you look to your BoundField now, you will see that the DataField is defined as "username":
<asp:BoundField HeaderText="Requested By" DataField="username" />
Either you change the column-name in your DataTable to "username" or you change the DataField in the BoundField to "Requested By".
To your second Problem:
Please read the How-To-Ask-FAQ:
Include just enough code to allow others to reproduce the problem. For
help with this, read How to create a Minimal, Complete, Valid Example.
You don't provide any research or a minimal example which shows us that you at least tried to find a solution.
So I will only give you hints for your "problem", if you got any question then regarding a not working code, please post a new question.
Get Cell Value in C# Gridview when Button clicked on row
How to send email in ASP.NET C#
Use the first link to get the user where the E-Mail should be sent to, and the second link provides the logic to send a E-Mail. Good luck!

ASP.NET Page does not refresh after running a DELETE SQL Query

I am using VS2005. Currently I have a delete linkButton in my gridview, and if I presses on it to delete a row, the GridView goes empty, and I will have to click on the link again to access the page.
Below is my codefor .aspx:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ondatabound="gv_DataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" OnCheckedChanged="UserSelector_CheckedChanged" runat="server" />
<asp:LinkButton ID="lnkDelete" runat="server" onclick="lnkDelete_Click" Text="Delete" CommandArgument='<%# Eval("Employee") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my code for .cs
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
}
I have tried assigning my delete query to SqlDataSource1 and select query to source2, but if that's the case, my delete query would not work.
I have also tried using IsPostBack on my PageLoad method, but the GridView goes empty as well after clicking on the delete button.
Currently both of my queries are assigned to SqlDataSource1, and once the query is deleted, the page just go blank, although the query is deleted.
May I know how can I refresh the page or reload the GridView table after the delete query is ran?
Thank you.
Thanks to the help from you guys, the problem is solved. Currently my working code is as follows:
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection("DATA-SOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
SqlDataSource1.SelectCommand = "SELECT * FROM [UserDB]";
SqlDataSource1.DataBind();
Response.Redirect("/Project/UserList.aspx");
I used a sql connection string for the delete query, and sqldatasource for the select query afterwards, finally refreshed the page by using response.redirect. Hope it helped newbies like me who met this error too.
Great thanks to all who provided help
Why are you assigning a DELETE command to the SelectCommand property ?
Just run the DELETE on a separate SqlCommand instance with ExecuteNonQuery and commit. Another option is to use DeleteCommand of the existing SqlDataSource.
Another point:
The way you build the DELETE SQL is vulnerable to a serious security problem called SQL injection - easiest and best way to avoid that is to use bind parameters!
First you should read up on what databinding in ASP.NET can do for you. (Then you won't have to write any codebehind for this scenario.)
Example: (Not tested in VS)
You should use the SqlDataSource's DeleteCommand to set the delete command and its parameters like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
SelectCommand="..."
DeleteCommand="DELETE FROM [UserDB] WHERE Employee=#Employee">
<DeleteParameters>
<asp:Parameter Name="Employee" />
</DeleteParameters>
</asp:SqlDataSource>
And the on the GridView, you should set the DataKeyNames property, and inside the ItemTemplate's Linkbutton you should set the CommandName property to "Delete" as shown below:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
ondatabound="gv_DataBound" DataKeyNames="Employee"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" runat="server"
OnCheckedChanged="UserSelector_CheckedChanged" />
<asp:LinkButton ID="lnkDelete" runat="server"
onclick="lnkDelete_Click" Text="Delete"
CommandArgument='<%# Eval("Employee") %>'
CommandName="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Try like this
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(<put your connectionstring here>);
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindTheGridView();
//or you can use SelectCommand of your SqlDataSource1 and can bind again simply.
}
EDIT:
public void BindTheGridView()
{
SqlConnection conn = new SqlConnection(Connstring);
string sql = "Select * from [UserDB]";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtb = new DataTable();
da.Fill(dtb);
conn.Close();
SqlDataSource1.DataSource = dtb;
SqlDataSource1.DataBind();
}
And you can call this for any time to bind the values.
It's wrong to run change operation (DELETE in your example) as a SelectCommand. SelectCommand must be used as it called - only to SELECTs.
Run the DELETE query separately, then run a SELECT command to show the relevant records for the grid.
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
Why are you using Delete query in SelectCommand. The query is open to SqlInjection attack. I would have used a stored procedure and verify the parameter before passing it to the procedure.
Moreover the Grid won't show/bind any data as your code is not return any data back. It is just deleting the data.
I guess you can do a gridview.DataBind() instead of sqlDatasource.databind. The gridviews databind internally performs the sqldatasource databind and also refreshes the gridview.

Categories