Asp.Net C# Delete row from dataTable gridview on button click - c#

I'm displaying a datatable that selects a number of elements from the database (IncomingsId, Type, Cost, Frequency) and I'm not sure how to delete a row when a button is clicked.
I've tried many solutions so far but nothing is working.
Here is the button I have within my Grid view
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:button id="DeleteRowButton" text="Delete Record" onclick="DeleteRowButton_Click" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind this page were I am creating the datatable.
SqlConnection con;
public _Default()
{
con = new SqlConnection(#"MySQLConnection");
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayRecord();
}
}
public DataTable DisplayRecord()
{
string userId = (HttpContext.Current.User.Identity.GetUserId());
SqlDataAdapter Adp = new SqlDataAdapter("select * from Incomings where AspNetUsersId = '" + userId +"'", con);
DataTable Dt = new DataTable();
Dt.AcceptChanges();
Adp.Fill(Dt);
grid1.DataSource = Dt;
grid1.DataBind();
return Dt;
}
public void DeleteRowButton_Click(object sender, EventArgs e)
{
}
Cheers in advance for any help. I'm sure it's a simple resolution

You need a way for your code to know which ID to delete. Here is how I would normally do it:
Replace your button with an ItemTemplate, and add the button in here instead:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("userId") %>' CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When you have the button this way, you now have access to a CommandArgument and CommandName attributes. Notice the argument I am passing is Eval("userId"), the command name (as you will see later) is used to recognize what action you want to execute (this could be anything, is just a name).
Replace the CommandArgument with whatever value(s) you want to pass to the server, using the name that came from the database/datasource (I am guessing it would be userId).
Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct CommandName:
public void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string userId = e.CommandArgument.ToString();
//do something with the id
}
}
Here you have to make sure the CommandName in your button, matches to whatever action you want to execute in the RowCommand. This should do the trick.
Don't forget to bind the event to your GridView:
<asp:GridView OnRowCommand="GridView1_RowCommand" ID="GridView1" runat="server">
...
</asp:GridView>

just use this for the front-end code
<asp:GridView ID="grid1" OnRowDeleting="OnRowDeleting" DataKeyNames="deleteR" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" style="width:100%" >
<columns>
<asp:TemplateField HeaderText="Delete Row">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" class="btn btn-primary" Text="Delete" CommandName="Delete" OnRowDataBound="OnRowDataBound" />
</ItemTemplate>
</asp:TemplateField>
And have this in behind it:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int deleteR= Convert.ToInt32(grid1.DataKeys[e.RowIndex].Values[0]);
//have a sql statement here that add's the parameter ID for the row you want to delete, something like
SqlCommand com = new SqlCommand ("Delete FROM yourdatabase Where yourID = #yourID"
com.Parameters.AddWithValue("#yourID", yourID)
}

What you're looking for is indeed a simple solution.
You can use a foreach loop to search all DataRows within the DataTable for some kind of ID.Here's an example of what I mean:
String s = "/* IncomingsId for what you want to delete */";
foreach (DataRow r in dt.Rows) {
if (r["IncomingsId"].ToString().Equals(s)) {
dt.Rows.Remove(r);
}
}

Just a quick update for anyone that's helped me, thanks for your advice.
Asp.Net has it's own built in AutoGenerateDeleteButton and I set that to true and ran a bit of code behind it.
A simple solution that really shouldn't have taken me all day to complete!

Related

Access HyperLink inside ItemTemplate inside TemplateField ASP.Net WebForms

I have an ASP TemplateField inside a data populated GridView as follows:
<asp:GridView ID="gvReport" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" OnRowDataBound="gvReport_RowDataBound" CssClass="table table-bordered">
<Columns>
<asp:BoundField DataField="Delete" HeaderText="Delete" SortExpression="Delete" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# "Edit?from=Delete&ID=" + Eval("ID") %>' ImageUrl="Assets/SmallDelete.png" SortExpression="PathToFile" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In other words, at the end of each row, there is a delete 'button'. I can tell whether a particular row/record has been deleted by checking the true/false value of the BoundField Delete in my code behind as follows:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell statusCell = e.Row.Cells[0];
if (statusCell.Text == "True")
{
//change ImageUrl of Hyperlink for this row
}
}
Right now, my icon is red for delete, but in the case that a record has already been deleted,
I would like to change the image to a different icon (a blue one).
How can I change this ImageUrl if statusCell evaluates to true?
ok, so we will need two parts here:
We need (want) to persist the data table that drives the grid).
The REASON for this?
We kill about 3 birds with one stone.
We use the data table store/save/know the deleted state
We use that delete information to toggle our image
(and thus don't have to store the state in the grid view).
We ALSO then case use that table state to update the database in ONE shot, and thus don't have to code out a bunch of database operations (delete rows). We just send the table back to the database.
In fact in this example, I can add about 7 lines of code, and if you tab around, edit the data? It ALSO will be sent back to the database. And this means no messy edit templates and all that jazz (which is panful anyway).
Ok, so, here is our grid - just some hotels - and our delete button with image:
markup:
<div style="width:40%;margin-left:20px">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-hover borderhide" >
<Columns>
<asp:TemplateField HeaderText="HotelName" >
<ItemTemplate><asp:TextBox id="HotelName" runat="server" Text='<%# Eval("HotelName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="ORDER BY FirstName" >
<ItemTemplate><asp:TextBox id="FirstName" runat="server" Text='<%# Eval("FirstName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" >
<ItemTemplate><asp:TextBox id="LastName" runat="server" Text='<%# Eval("LastName") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" >
<ItemTemplate><asp:TextBox id="City" runat="server" Text='<%# Eval("City") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="cmdDelete" runat="server" Height="20px" Style="margin-left:10px"
ImageUrl="~/Content/cknosel.png"
Width="24px" OnClick="cmdDelete_Click"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdDeleteAll" runat="server" Text="Delete selected" Width="122px"
OnClientClick="return confirm('Delete all selected?')" />
</div>
Ok, and the code to load up the grid - NOTE WE persist the data table!!!!!
Code:
DataTable rstTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
else
rstTable = (DataTable)ViewState["rstTable"];
}
void LoadGrid()
{
// load up our grid
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstTable.Clear();
rstTable.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstTable;
GridView1.DataBind();
}
ViewState["rstTable"] = rstTable;
}
Ok, so far, real plain jane. The result is this:
Ok, so now all we need is to add the delete button click event.
That code looks like this:
protected void cmdDelete_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow rRow = (GridViewRow)btn.Parent.Parent;
DataRow OneRow = rstTable.Rows[rRow.DataItemIndex];
// toggle data
if (OneRow.RowState == DataRowState.Deleted)
{
// undelete
OneRow.RejectChanges();
btn.ImageUrl = "/Content/cknosel.png";
}
else
{
// delete
OneRow.Delete();
btn.ImageUrl = "/Content/ckdelete.png";
}
}
Again, really simple. But NOTE how we use the data table row state (deleted or not).
And this ALSO toggles the image for the delete button.
So, we don't have to care, worry, or store/save the sate in the grid.
So, if I click on a few rows to delete, I now get this:
So far - very little code!!!
Ok, so now the last part. the overall delete selected button. Well, since that is dangerous - note how I tossed in a OnClientClick event to "confirm the delete. if you hit cancel, then of course the server side event does not run.
But, as noted since we persisted the table? Then we can send the table deletes right back to the server without a loop. The delete code thus looks like this:
protected void cmdDeleteAll_Click(object sender, EventArgs e)
{
// send updates (deletes) back to database.
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels WHERE ID = 0",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daUpdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daUpdateBuild = new SqlCommandBuilder(daUpdate);
daUpdate.Update(rstTable);
}
LoadGrid(); // refesh display
}
So, note how easy it is to update (delete) from the database. If you look close, I used text boxes for that grid - not labels. The reason of course is that if the user tabs around in the grid (and edits - very much like excel), then I can with a few extra lines of code send those changes back to the database. In fact the above delete button code will be 100% identical here (it will send table changes back with the above code. So, if we add rows, edit rows then the above is NOT really a delete command, but is in fact our save edits/deletes/adds command!

gridview findcontrol returning nothing empty string(Blank)

I am trying to pass a session value from a gridview select row using GridView1_RowEditing1 event. i am able to get session value for primarykey (p.key) but the Associate_ID returns empty.
C# Code behind
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
int primarykey = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
string name = Convert.ToString(GridView1.Rows[e.NewEditIndex].FindControl("Associate_ID"));
Session["Number"] = primarykey;
Session["Name"] = name;
//redirect
Response.Redirect("updatee.aspx");
}
.ASPX
<asp:TemplateField HeaderText="Associate_ID" SortExpression="Associate_ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
OUTPUT:
Key: 5
Name:
As you can see i am not getting Associate_ID for selected field.
Also tried using
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("Associate_ID"));
but there was no result, the grid has multiple columns and rows (8*15)
tried suggestions on gridview findcontrol returning empty "" and tried stopping re-binding the GridView on the PostBack.
removed DataSourceID from gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//DataSourceID = "SqlDataSource1"
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
None of this helped. I am still getting a blank value for Associate_ID.
i am unable to see where the issue is. Please help!
You are trying to find the Control Associate_ID with FindControl. But it does not exist. Either find TextBox1 or rename the TextBox to Associate_ID.
<EditItemTemplate>
<asp:TextBox ID="Associate_ID" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
//or
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("TextBox1"));
UPDATE
I see the problem, somehow you are trying to access those control before the edit state has been activated by rebinding the GridView. The edit index has not been set. So place this before the FindControl.
GridView1.DataSource = yourSource;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
Thank you so much VDWWD, i was finally able to get it to work.
The problem was i was not able to use get my 'TextBox' element in gridview using FindControl.
The solution was to not re-binding the GridView on the PostBack of the page and edit index on the RowEditing event.
This is what my working code looks like, is any one ever comes across a similar issue
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txt = GridView1.Rows[e.NewEditIndex].FindControl("TextBox1") as TextBox;
string name = txt.Text;
}
.ASPX
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
</EditItemTemplate>

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;

ASP.NET c# Checkboxlist in a template field

I a newbie to asp.net. I have created a DB table in sqlserver with 3 columns; ImageID, Filename & Score.
FileName is C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg.
Using C# asp.net, I have created a GridView. This Gridview should populate
(column 1)ImageID and get the image from the Filename (column2) and I have 2 Checkboxlist created as shown below which should accept score for the images from user and save it into the DB table.
Question 1 .
I am able to populate Image ID, but Images are not getting populated.
Question 2.
I do not know how to access the checkboxlist since it is in template. The checked is in the default select and doesn't change even if I click on it. Which method/property should be used to do save the selection to the database. Here's my code
<form id="form1" runat="server">
<p style="height: 391px">
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:CheckBoxList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test">
<asp:ListItem Selected="True" Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" Width="130px" />
<asp:Button ID="Button2" runat="server" OnClientClick="javaScript:window.close(); return false;" Text="Exit" Width="102px" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
</form>
public string sqlSel = #"SELECT TOP 3 [ImageID],FileName FROM [db1].[ImagesTest] where [Score] is null";
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmdSel = new SqlCommand(sqlSel, connection);
SqlDataReader reader1 = cmdSel.ExecuteReader();
while (reader1.Read())
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
}
private DataSet GetData(string cmdSel)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter(cmdSel,con);
sda.Fill(ds);
}
catch (Exception ex)
{
Response.Write("IN EXCEPTION "+ex.Message);
return null;
}
return ds;
}
Thanks for ur time
Rashmi
There are several issues with your code, here is what it should be fixed:
How to fix the images (Question 1)
As #Guilherme said in the comments, for images use URLs instead of disk paths.
Replace the images disk paths C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg to something like Images/beads.png and Images/scenary.jpeg.
For this to work, you will need to have a folder named Images that contains these two files on the same directory level as your .aspx file.
Adjust your GridView1 declaration in the ASPX file
On your GridView1 declaration you should:
attach a handler to the OnRowDataBound event. This will allow you to properly bind the Score dataset column to the Score gridview column
set the DataKeyNames property on the grid to what should be the primary key for your images table (in this case DataKeyNames="ImageID")
use a RadioButtonList instead of a CheckboxList, because according to your dataset you can only set one value, which is what the RadioButtonList does. The CheckboxList is normally used when multiple selection is needed.
attach a handler to the SelectedIndexChanged event on the RadioButtonList. This will allow you to save the new values to the database (Question 2)
Here's how your GridView declaration should look like:
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ImageID">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="RadioButtonList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:RadioButtonList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged">
<asp:ListItem Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:RadioButtonList>
<!-- UPDATED! - keep the old values in a hidden field -->
<asp:HiddenField runat="server" ID="hfOldScore" Value='<%# Eval("Score") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Adjust your code behind value in your .ASPX.CS file (Question 2)
On the code behind, you will also need to:
Make sure you are binding to the GridView only once in the Page_Load event, by checking the IsPostBack property
(Optional, but recommended) Move the logic of getting data (with the SQLConnection code) in a separate method that will handle only data retrieval
Implement the handler for the OnRowDataBound event. This will bind any values from the Score column to the RadioButtonList control
Implement the handler for the SelectedIndexChecked event of the RadioButtonList control. This will allow you to save to the database the new values
Finally, here's the entire code-behind code:
protected void Page_Load(object sender, EventArgs e)
{
//bind only the first time the page loads
if (!IsPostBack)
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
private DataSet GetData(string cmdSel)
{
//normally you should query the data from the DB
//I've manually constructed a DataSet for simplification purposes
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
dt.Columns.Add(new DataColumn("FileName", typeof(string)));
dt.Columns.Add(new DataColumn("Score", typeof(int)));
dt.Rows.Add(100, #"Images/beads.png", 0);
dt.Rows.Add(200, #"Images/moreimages/scenary.jpeg", 3);
dt.Rows.Add(300, #"Images/moreimages/scenary.jpeg", 5);
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
//UPDATED - iterate through all the data rows and build a dictionary of items
//to be saved
Dictionary<int, int> dataToUpdate = new Dictionary<int, int>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int imageID = (int)GridView1.DataKeys[row.RowIndex].Value;
int oldScore;
int newScore;
int.TryParse((row.FindControl("hfOldScore") as HiddenField).Value, out oldScore);
int.TryParse((row.FindControl("test") as RadioButtonList).SelectedValue, out newScore);
if (oldScore != newScore)
{
dataToUpdate.Add(imageID, newScore);
}
}
}
//update only the images that were changed
foreach (var keyValuePair in dataToUpdate)
{
SaveToDB(keyValuePair.Key, keyValuePair.Value);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//we are only interested in the data Rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dataRow = (e.Row.DataItem as DataRowView).Row;
//manually bind the Score column to the RadioButtonlist
int? scoreId = dataRow["Score"] == DBNull.Value ? (int?)null : (int)dataRow["Score"];
if (scoreId.HasValue)
{
RadioButtonList test = e.Row.FindControl("test") as RadioButtonList;
test.ClearSelection();
test.SelectedValue = scoreId.Value.ToString();
}
}
}
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList test = sender as RadioButtonList;
GridViewRow gridRow = test.NamingContainer as GridViewRow;
//obtain the current image Id
int imageId = (int)GridView1.DataKeys[gridRow.RowIndex].Value;
//obtain the current selection (we will take the first selected checkbox
int selectedValue = int.Parse(test.SelectedValue);
//UPDATED! - saves are now handled on the Save button click
//SaveToDB(imageId, selectedValue);
}
private void SaveToDB(int imageId, int score)
{
//UPDATED!
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.Parameters.Add("#ImageID", imageId);
command.Parameters.Add("#Score", score);
command.CommandText = #"update [db1].[ImagesTest] set Score = #Score where [ImageID] = #ImageID";
command.ExecuteNonQuery();
}
}
}
UPDATED!
The declaration of the GridView1 now contains a hidden field containing the Score value. You can use this hidden field to determine which row has changed, so you can trigger a save only on the changed ones
Save is now done on the click of the Save button, by iterating through the rows of the grid an building a Dictionary<int,string> to keep only the changes.
SaveToDB method should work, but I cannot test this myself.
Question 2:
To access your checkbox you can use.
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("test");
For Question 1
Instead of ImageField you can use use ASP:Image in Templatefield like this
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:Image ID="imageControl" runat="server" ImageUrl='<%# Eval("Filename") %>'></asp:Image>
</ItemTemplate>
</asp:TemplateField>
For Question 2
This is one of the example for how to access each Checkbox list inside gridview
For Each gvr As GridViewRow In Gridview1.Rows
If (CType(gvr.FindControl("CheckBox1"), CheckBox)).Checked = True Then
ReDim uPrimaryid(iCount)
uPrimaryid(iCount) = New Integer
uPrimaryid(iCount) = gvr.Cells("uPrimaryID").Text
iCount += 1
End If
Next

Binding RowCommand to fire when any cell in a row is clicked

My GridView basically displays a summarized version of data in the database.
What I want to do is set it up so that when you click anywhere in a row in the GridView, it should execute a set procedure that'll hide the panel that contains the GridView and display a panel that will show you the details of the item you clicked.
<asp:Panel runat="server" ID="pnlList">
<div class="rightalign">
<asp:Label runat="server" ID="lblCount"></asp:Label>
</div>
<asp:GridView runat="server" ID="gvItems" DataKeyNames="mailid"
AutoGenerateColumns="false" onrowdatabound="gvItems_RowDataBound"
Width="100%" OnSelectedIndexChanged="gvItems_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="firstname" HeaderText="From" SortExpression="firstname" />
<asp:BoundField DataField="datesent" HeaderText="Date" SortExpression="datesent" DataFormatString="{0:yyyy/MM/dd HH:mm}" />
<asp:BoundField DataField="subject" HeaderText="Subject" SortExpression="subject" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMail">
<p>From: <asp:Label runat="server" ID="lblFrom"></asp:Label><br />
Sent On: <asp:Label runat="server" ID="lblDate"></asp:Label><br />
Subject: <asp:Label runat="server" ID="lblSubject"></asp:Label></p>
<p><asp:Label runat="server" ID="lblMessage"></asp:Label></p>
</asp:Panel>
I figured I'd use the SelectedIndexChanged event, but I'm not sure how to actually make it fire off clicks on the cells.
Here's the code I've got:
protected void gvItems_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gvItems.SelectedIndex;
string mailid = gvItems.DataKeys[index].Value.ToString();
getMailDetail(mailid);
pnlMail.Visible = true;
}
protected void getMailDetail(string id)
{
int mailid = int.Parse(id);
MySqlContext db = new MySqlContext();
string sql = "select m.datesent, m.subject, m.message, u.firstname, u.lastname from mail m inner join users u on m.senderid = u.userid where m.mailid = #id";
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter() { ParameterName = "#id", MySqlDbType = MySqlDbType.Int32, Value = mailid });
MySqlDataReader dr = db.getReader(sql, args);
if (dr.HasRows)
{
dr.Read();
lblFrom.Text = (string)dr["firstname"] + " " + (string)dr["lastname"];
lblDate.Text = (string)dr["datesent"];
lblSubject.Text = (string)dr["subject"];
lblMessage.Text = (string)dr["message"];
}
dr.Close();
}
How can I make clicks on the cells in a row fire an event that'll do the work I need done?
Any help will be appreciated!
I can see two possible solutions here. First - handle click on the row on client side, send Ajax request to some HttpHandler that will return you necessary mail details, and display the returned info. Steps to achieve this:
Assign a client side handler too row click:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "showMailDetails(" + DataBinder.Eval(e.Row.DataItem, "id") + ")";
}
}
And define the client side function:
function showMailDetails(mailId) {
$.get(
url: 'url to HttpHandler here',
data: {id: mailId},
success: function(data) {
var pnlMail = $('#<%= pnlMail.ClientID %>');
// display data here
pnlMail.show()
});
}
Another way is to handle click on client side and then emulate RowCommand event by doing something like this:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = ""javascript:__doPostBack('" + gvItems.ClientID + "','MailDetailsCommand$" + DataBinder.Eval(e.Row.DataItem, "id") + "')";
}
}
And then on server side go like you already did, just in RowComamnd handler:
protected void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MailDetailsCommand") {
// ...
}
}
Although I would not recommend this method - using _doPostBack manully is not considered as a best practice.
you give a template field which consist the button or a button field and then you can the give the commandname as something and then you can use the gridview commandeventargs and based on the commandname you can do whatever you want, and you can use the OnRowCommand to fire an event :D hope this will help you .....
You can even go for adding the onclick attribute to the cell in the RowDataBound Event, if there are any restrictions of not having the button field or like that

Categories