GridView Not Updating After Updating The Database - c#

I have a GridView. I'm displaying all the users in the system in this GV and I have a button to Delete the user by updating the deleted column in the table to 1.
<asp:GridView ID="GridView1" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging"
PageSize="20" runat="server" OnRowCommand="GridView1_OnRowCommand"
DataKeyNames="Id, Email" EnableViewState="false" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="buttonDelete" runat="server" CommandName="Remove" Text="Delete"
CommandArgument='<%# Eval("Id") + ";" +Eval("Email")%>'
OnClientClick='return confirm("Are you sure you want to delete this user?");' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
string cmdName = e.CommandName;
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ';' });
string UserRowID = commandArgs[0];
string Email = commandArgs[1];
string sql = "UPDATE USERS " +
"SET [Deleted]= 1" +
"WHERE ROWID= " + UserRowID;
DataTable table = PublicClass.ExeSql_Table(sql, "Utility");
GridView1.DataBind();
}
When I click on Delete, it updates the database but it does not delete the row from the GV. I need to refresh the page or click twice to delete the row. How can I do it with one click?

You just have to load the DataSource again and bind it to the GridView:
DataTable table = PublicClass.ExeSql_Table(sql, "Utility");
GridView1.DataSource = table; // <-- you've forgotten this
GridView1.DataBind();

When you delete the row , rebind your grid with data.

Specify OnCommand Field in your linkbutton "buttonDelete"
Example :
OnCommand = "Delete_Record"
And write following code in aspx.cs
protected void Delete_Record(object sender, CommandEventArgs e)
{
GridView1.DataSource = table;
GridView1.DataBind();
}

Related

I can't seem to find the checkbox I put in a gridview for selection of rows

I am working with a gridview which I want to select a row and then put the row in a datatable to bind with a repeater control. I am having trouble finding the selected rows using the checkbox control that I had put in the gridview. I have searched the internet and have found some information on finding controls recursively. I can find a checkbox control however the results are always a "false" checkedbox. My question, Do I need to do something when the checkbox is checked in order for the gridview to know that there was a change? The checkbox is not bound to any data in my datatable is is only used for selection purposes.
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#191970" HeaderStyle-ForeColor="White" ShowFooter="false" RowStyle-Wrap="false"
AlternatingRowStyle-BackColor="#80993c" AlternatingRowStyle-ForeColor="White" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" AllowSorting="true" ShowHeaderWhenEmpty="true" EmptyDataText="No Notaries found with the specified criteria." CssClass="GridView1" OnSorting="GridView1_Sorting1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="notaryselect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="firstname" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="lastname" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="suffix" HeaderText="Suffix" />
<asp:BoundField DataField="city" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="state" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="zipcode" HeaderText="Zip Code" SortExpression="Zipcode" />
<asp:TemplateField>
<HeaderTemplate>Cell Phone</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hyperCellPhone" runat="server" ForeColor="Gold"
NavigateUrl='<%# Eval("cellphone", "tel:{0}") %>'
Text='<%# Eval("cellphone") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Email</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hyperEmail" runat="server"
NavigateUrl='<%# Eval("email", "mailto:{0}") %>'
Text='<%# Eval("email") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="county" HeaderText="County" SortExpression="County" />
<asp:BoundField DataField="lat" HeaderText="Latitude" />
<asp:BoundField DataField="long" HeaderText="Longitude" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Width="50%" />
</asp:GridView>
Control check = FindControlRecursive(GridView1.Rows[i], "notaryselect");
The above line is some code just to find the checkbox. I was experimenting and found that a checkbox is returned but no matter what they all come back false which is leading me to think that since they are set to unchecked or false at the start I need to do something but I am just not sure. Everything I find on the internet shows it should work. Let me know what your thoughts are.
Here is the code for the recursive function.
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control c in Root.Controls)
{
Control fc = FindControlRecursive(c, Id);
if (fc != null)
return fc;
}
return null;
}
I found that code on this site from a similar question and wanted to see if that worked.
You don't need any recursive function.
So, say this gv with a check box:
(it can be set to a value in the table, or not - does not matter).
So, this gv:
runat="server" CssClass="table" AutoGenerateColumns="false"
width="42%" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server"
Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="view"
CssClass="btn" OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
GridView1.DataSource = rstData;
GridView1.DataBind();
}
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And we now see/get this:
Ok, so for the click/view button, we have this code:
protected void cmdView_Click(object sender, EventArgs e)
{
Button btnView = (Button)sender;
GridViewRow gRow = (GridViewRow)btnView.NamingContainer;
Debug.Print("Row index click = " + gRow.RowIndex);
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("Database PK id = " + PK);
CheckBox ckActive = (CheckBox)gRow.FindControl("chkActive");
if (ckActive.Checked)
Debug.Print("check box is true");
else
Debug.Print("Check box is false");
}
output:
Row index click = 2
Database PK id = 7
Check box is false
So, above is a row click sample.
But, for all rows, then this:
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox ckBox = (CheckBox)gRow.FindControl("chkActive");
Debug.Print($"Row index = {gRow.RowIndex} Checkbox value = {ckBox.Checked.ToString()}");
}
output:
Row index = 0 Checkbox value = True
Row index = 1 Checkbox value = False
Row index = 2 Checkbox value = False
Row index = 3 Checkbox value = True
Row index = 4 Checkbox value = False
Row index = 5 Checkbox value = True
Row index = 6 Checkbox value = True
Row index = 7 Checkbox value = True
And of course, above could also display the database PK value, and quite nice is such values don't have to be exposed client side in the GV.
eg:
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID];

How can i hold gridview row selected values into a string in asp.net

I have gridview control it contains 6 columns when i click 6th column row of gridview i need to selecte that contains columns row text into a string. how can i take here i am taking commandargument is a string and how can i take another column names text
my code:
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="" ItemStyle-ForeColor="White" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="SName" HeaderText="SName" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Size" HeaderText="Size(MB)" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
CommandName="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No." Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string ID1;
if (e.CommandName == "Download")
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
Label Itemid = (Label)GridView1.Rows[rowIndex].FindControl("lblID");
ID1 = (Itemid).Text;
Session["ID"] = ID1;
string filename = e.CommandArgument.ToString();
//here how can i hold another column text
}
}
I have a easiest way to do this same thing...
<asp:Label ID="lblName" runat="server" Text='<%#Eval("ID").ToString() +", "+ Eval("OtherCoulmn").ToString() %>'></asp:Label>
--- hope it helps
Also the best way is to do something like this
((MyObject)Container.DataItem).MyProperty where MyObject is the Model which you bind with grid and property which you wan to use in rowcommand its clean .
Simply follow the bellow code sample:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
Label lblId = gvCipamMember.Rows[gvr.RowIndex].FindControl("lblPersonId") as Label;
cmd = new SqlCommand("SELECT Id,Res_Person,Email_ID,Mobile_NO,Cipam_Flag FROM Responsibilty_Master WHERE Id=#Id", con.MyConnection);
cmd.Parameters.AddWithValue("#Id", Convert.ToInt32(lblId.Text.ToString()));
dt = new DataTable();
con.MyConnection.Open();
dt.Load(cmd.ExecuteReader());
if (dt.Rows.Count > 0)
{
txtPersonName.Text = dt.Rows[0]["Res_Person"].ToString();
txtEmail.Text = dt.Rows[0]["Email_ID"].ToString();
txtMobileNo.Text = dt.Rows[0]["Mobile_NO"].ToString();
if(Convert.ToBoolean(dt.Rows[0]["Cipam_Flag"].ToString())==true)
{
chkbCipamFlag.Checked = true;
}
}
}

selected row in gridview

I have two table in sql server as follow
PatientDetail - 1st table name
PatientId --- primary key
firstname
lastname
Patexam - 2nd table name
PId ---- foreign key of first table PatientId
Exam
I have one gridview in the page which shows all the column of first table as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex], FROM [PatientDetails]"></asp:SqlDataSource>
I have one button with the text value = "formatric3d"
Now when i select one row in gridview and then click on button with
value = "formatric3d",
so on click event I want to insert the selected row patientid as well as button text value = "formatric3d" into the table name Patexam.
That means PId equal to PatientId which is selected on gridview and Exam equal to button text value = "formatric3d".
Is this something you want?
<asp:Button runat="server" ID="btnExam" Text="formatric3d" OnClick="Exam_ClickHandler" />
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<h3>Patient Exams</h3>
<asp:DataList runat="server" ID="dtlExams">
<ItemTemplate>
<%#Eval("Exam") %>
</ItemTemplate>
</asp:DataList>
//////////////// tree view
<asp:TreeView runat="server" ID="tvExams">
</asp:TreeView>
On code behind page:
protected void Exam_ClickHandler(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chk");
if (chk.Checked)
{
string patientId = ((Label)row.FindControl("lblPID")).Text;
string exam = ((Button)sender).Text;
///your insertion query goes here.
///
GetPatientExams(patientId);
}
}
}
protected void Patient_ExamHandler(object sender, CommandEventArgs e)
{
string patientId = e.CommandArgument.ToString();
GetPatientExams(patientId);
}
private void GetPatientExams(string pid)
{
DataTable exams = "Get exam data from db by pid";
dtlExams.DataSource = exams;
dtlExams.DataBind();
//////////////// tree view
TreeNode tnnn;
foreach (DataRow row in exams.Rows)
{
tnnn = new TreeNode(exams["PRODSHORT"].ToString());
tvExams.Nodes.Add(tnnn);
}
}

Nested GridView Problems

I am trying to nest one gridview within another, but I cannot get the data to populate in the second grid view. I am getting an error when trying to set the data source of the second data grid (saying it is null). Can anyone help?
Here is the aspx page:
<div id="divSource" runat="server" align="center">
<asp:GridView ID="Source" runat="server" AutoGenerateColumns="False" DataKeyNames="sourceLineItem" CSSClass="viewSourceGrid" OnRowDataBound="PopulateDateCodes">
<Columns>
<asp:TemplateField InsertVisible="False" HeaderStyle-Width="70px">
<ItemTemplate>
<asp:Label CssClass="sourceHeader" runat="server" Text= '<%# "Source: " + (Container.DataItemIndex + 1).ToString() %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="nfdBroker" HeaderText="NFD/Broker" InsertVisible="False" ReadOnly="True" SortExpression="nfdBroker" />
<asp:BoundField DataField="locationDescription" HeaderText="Material Location" SortExpression="materialLocation" />
<asp:BoundField DataField="origPkg" HeaderText="Original Packaging?" SortExpression="origPkg" />
<asp:BoundField DataField="oemCC" HeaderText="OEM C of C? " InsertVisible="False" ReadOnly="True" SortExpression="oemCC" />
<asp:BoundField DataField="minBuyQty" HeaderText="Minimum Buy Qty" SortExpression="minBuyQty" />
<asp:BoundField DataField="deliveryInfo" HeaderText="Delivery" SortExpression="delUOM" />
<asp:TemplateField InsertVisible="False" HeaderText="Date Codes" >
<ItemTemplate>
<asp:GridView ID="DateCodeGrid" runat="server" InsertVisible="False" DataKeyNames="dateCode" CSSClass="viewSourceGrid" >
<Columns>
<asp:BoundField DataField="dateCode" SortExpression="dateCode">
<ItemStyle Width="20%" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and then here is the code behind:
public partial class Controls_ViewSource : System.Web.UI.UserControl
{
//Set the Source Line Item
public int SourceLineItem { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.SourceLineItem = SourceLineItem;
RequestDB db = new RequestDB();
DataSet sources = db.GetSource(int.Parse(Request.QueryString["requestNumber"]), SourceLineItem);
Source.DataSource = sources;
Source.DataBind();
}
protected void PopulateDateCodes(object sender, GridViewRowEventArgs e)
{
RequestDB db = new RequestDB();
int index = e.Row.RowIndex;
GridView gv = (GridView)Source.Rows[0].FindControl("DateCodeGrid");
//int sourceLineItem = int.Parse(Source.DataKeyNames[0].ToString());
//Response.Write(Source.DataKeyNames[0].ToString());
DataSet dateCodes = db.GetDateCodes(71);
gv.DataSource = dateCodes;
gv.DataBind();
}
}
You would need to find the nested grid view in the row that is being data bound:
GridViewRow row = e.Row;
You need to make sure you are only doing this for data rows, not header or footer rows:
if(row.RowType == DataControlRowType.DataRow)
{
// Find the nested grid view
GridView nested = (GridView)row.FindControl("DateCodeGrid");
// The rest of your code for binding the nested grid view follows here
}

Passing Value when Select on GridView to another page

I have a GridView which is showing some data:
Entity_ID (PK)
Name
Description
Now I am enabling Select in my GridView. I need to pass Entity_ID to another page and in this page I am showing more contents for this Entity_ID.
How should I pick the Entity_ID value and pass it in as Query String? I have this code:
ProductsDataGridView.SelectedRows(0).Cells(1).Value.ToString()
Any responses will be appreciated! Thank you.
Add a new item template column in you grid and add the select link as below.
<asp:TemplateField HeaderText="View Details">
<ItemTemplate>
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/detailspagename.aspx?ID={0}", Eval("Entity_ID")) %>'>Select</asp:HyperLink>
</ItemTemplate>
This is what I did:
protected void gvAgentList_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvAgentList.SelectedRow;
Response.Redirect("~/FrontEnd/Registration.aspx? EntityID=" + row.Cells[0].Text);
}
Use the OnRowSelected event. Once it calls that you can get the selected row and then the entity id. Next you can build a string with the entity id in the query string and response.redirect to that page.
You can also use DataKeys
set DataKeys='Entity_ID'
In the code behind you can access the same as selectedrow.DataKeys[rowindex]["Entity_ID"]
here selected row is the one you selected , rowindex the index and you get the corresponding Entity_ID
#GSGuy:
<asp:GridView runat ="server" ID = "gvAgentList"
AllowPaging = "True"
AutoGenerateSelectButton="True" AllowSorting="True" BackColor="#E8E8E8"
BorderColor="#003399" BorderStyle="Solid" BorderWidth="1px" Height="375px"
Width="823px" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1" onselectedindexchanged="gvAgentList_SelectedIndexChanged">
<AlternatingRowStyle ForeColor="#0066CC" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:TemplateField HeaderText="View Details">
<ItemTemplate>
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/detailspagename.aspx?ID={0}", Eval("Entity_ID")) %>'>Select</asp:HyperLink>
</ItemTemplate>
</Columns>
<HeaderStyle ForeColor="#3366FF" />
</asp:GridView>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string fname, lname;
fname = GridView1.Rows[e.NewEditIndex].Cells[0].Text;
Session["fname"] = fname;
lname = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
Session["lname"] = lname;
Response.Redirect("gridpass.aspx");
}
On gridpass.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Session["fname"].ToString();
TextBox2.Text = Session["lname"].ToString();
}
there are several approaches how to pass data between pages:
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
the query string is ok if you don't mind the url will contain the ID
you can also consider Page.PreviousPage from the options above, which seems reasonable in your case

Categories