How to update database in SQL Server when I have checkbox in gridview? - asp.net

I tried to make a message board.
After someone leave message, manager can check message context can be show for others or not.
I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.
If I checked checkbox, and click "sent" button, SQL Server data will be updated.
If I would like to update checkbox result into SQL Server data, what should I do?
This is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>
And this is my aspx.cs - if I use foreach, it can't update into my database
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
if (reply.Checked)
{
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1' WHERE (id = {id})", sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close ();
DataBind();
}
}
}
If I use for, it showed error about "datakey array"
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
int messageCheck, displayCheck;
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
if (message.Checked == true)
{
messageCheck = 1;
SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd1.ExecuteNonQuery();
}
else
{
messageCheck = 0;
SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd2.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
Without javascript, how could I do it?
Thanks for you all

Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.
However, for templated columns, we have to use find control.
And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.
Ok, so here is a GV with both datafiles (the cells()), and also check box.
We will select the check boxes, and then with a save button, send changes back to database.
So, our markup:
<div style="width:50%;padding:25px">
<asp:GridView ID="GVHotels" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save changes" CssClass="btn"/>
</div>
And now our code to fill out above could be say this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we see this:
Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.
but, we just loop the GV, and execute updates. (if I have time, I'll try and post the 2nd more cool approach).
So, our button to update/save changes (for check boxes). Could be this:
protected void cmdSave_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
conn.Open();
string strSQL = "UPDATE tblHotels Set Smoking = #S, Balcony = #B " +
"WHERE ID = #ID";
foreach (GridViewRow gRow in GVHotels.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
}
Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.
Note that you would continue to use cells() collection for NON templated columns. But for any templated column - you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.
We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows - we actually keep the connection open for the update - and thus not a big deal either way.

Kindly check with this code
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each row In GridView1.Rows
Dim chk As CheckBox = row.FindControl("CheckBox2")
If chk.Checked Then
'sql update query
Else
End If
Next
End Sub

Related

How to add text to asp:BoundField in GridView?

I have the following GridView in which data is being fed from the OleDB Database.
<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server">
<Columns>
...
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
...
</Columns>
</asp:GridView>
And I am reading the contents from the Database and printing in the GridView in the following manner:
protected void ShowGridView()
{
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string sqlQuery = "select * from ... ";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
}
What I want to do: I want to append % symbol to the contents of interestRate column in the GridView such that they should be displayed as 3% instead of 3. But the % symbol should not be inserted into the Database. In other words, the % symbol should only be used for display purposes in the GridView.
Depending on how you store the interest rate in the database will depend on which one of the below solutions remedy your question,
If the interest rates are formatted such that 0 = 0% and 1 = 100% you can use:
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" DataFormatString="{0:p}"/>
Documentation
Otherwise you will need to do a template
<columns>
<asp:TemplateField HeaderText="Interest Rate:">
<ItemTemplate>
<asp:Literal ID="IntRate" runat="server" Text='<%# Eval("InterestRate") + "%" %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</columns>
Updating answer as per comments below
protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
var row = GridViewSavingsTracker.Rows[index];
var interestRate = ((Literal row.FindControl("IntRate")).Text;
if (e.CommandName == "SomeCommand")
{
TextBoxInterestRate.Text = interestRate;
}
}

add date to database if checkbox checked in gridview

I have an Ordering system showing Orders that have been received and also orders that are outstanding. If the Order is received and the checkbox is then checked I would like to add the date to the database when the order was received. Obviously I would only like to add the date to the row that has been checked. Thanks in advance.
relevant HTML as follows:
<asp:GridView ID="gvOpenOrders" runat="server" AutoGenerateColumns="False" Width="100%" CellPadding="4" ForeColor="#333333"
GridLines="None" DataKeyNames="PurchaseOrderID" AllowPaging="True" AllowSorting="True"
OnSorting="gvOpenOrders_Sorting" EnableViewState="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="15" ViewStateMode="Enabled">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Is Received" SortExpression="IsReceived">
<ItemTemplate>
<asp:CheckBox ID="chkRcvd" runat="server" AutoPostBack="true" Checked='<%# Bind("IsReceived") %>' Enabled='<%# Eval("IsReceived") = False %>' OnCheckedChanged="chkRcvd_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
I am currently updating the database when a Update Received button is clicked, see below:
Protected Sub btnUpdateReceived_Click(sender As Object, e As EventArgs) Handles btnUpdateReceived.Click
con.Open()
For Each row As GridViewRow In gvOpenOrders.Rows
Dim purchaseOrderID As Integer = Convert.ToInt32(gvOpenOrders.DataKeys(row.RowIndex).Values(0))
Dim isReceived As Boolean = TryCast(row.FindControl("chkRcvd"), CheckBox).Checked
cmd.CommandText = "usp_UpdatePurchaseOrder"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#OrderID", purchaseOrderID)
cmd.Parameters.AddWithValue("#IsReceived", isReceived)
cmd.ExecuteNonQuery()
Next
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
I know that there is a checkbox_CheckedChanged event but I am unsure how to use it.
You can add this code in CheckedChanged event:
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked)
{
string date = DateTime.Today.ToString("dd-MM-yyyy");
}
Hope could convert it into VB's code.
As I think only one modification can find your solution.
Try this:
string strDate=stirng.Empty;
foreach (GridViewRow rw in grid1.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
strDate = ((Label)rw.FindControl("lblDate")).Text;
}
}
protected void chkRcvd_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked)
{
string date = DateTime.Today.ToString("dd-MM-yyyy");
}
}

asp.net delete item from gridview

im using asp.net and sql server . i have a gridview in my asp form which is binded in my form load . i wrote a command on my delete button but it doesn't effect .
here is my code :
ASP.net :
<asp:TemplateField HeaderText="#" ItemStyle-CssClass="Company_Grid_Checkbox">
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fldCountPhoto" HeaderText="تعداد عکس" />
<asp:BoundField DataField="fldActive" HeaderText="موقعیت نمایش" />
<asp:BoundField DataField="fldPrice" HeaderText="قیمت" />
<asp:BoundField DataField="fldYear" HeaderText="سال" />
<asp:BoundField DataField="fldModel" HeaderText="مدل" />
<asp:BoundField DataField="fldCompany" HeaderText="کمپانی" />
<asp:BoundField DataField="fldTbl_UserCarID" HeaderText="ID" />
</Columns>
C# code :
protected void btn_del_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label1.Text = (i++).ToString();
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
string id = row.Cells[7].Text;
Label1.Text = "id";
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString);
string sqlStatement = "DELETE FROM tbl_Usercar WHERE fldTbl_UserCarID = #fldTbl_UserCarID";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#fldTbl_UserCarID", id);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
}
}
}
in the above codes i wrote only the part of gridview and i didnt write other parts .
My guess would be that you are binding the grid in Page_Load without checking for IsPostBack. This would cause your grid to rebind before your button click event, which resets your checkboxes.

how to delete a row on gridview with a JavaScript button and remain on the same page

I am displaying a set of records through gridview, and edit and delete
buttons next to them. I am having a problem in the record deletion section. The behavior I want is the following: the user clicks the button, a JavaScript validation function is called and after the button click the records are deleted, but the user remains on the same page with the rest of the records. How can I do this while remaining on the same page?
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div>
<br />
<asp:HyperLink NavigateUrl="~/Entry.aspx" runat="server" text="Add New Record" />
</div>
<div>
<asp:GridView runat="server" ID="grdView" AutoGenerateColumns="false" Height="100%"
Width="100%" onselectedindexchanged="grdView_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="Prod_Id" HeaderText="product id " HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Prod_Name" HeaderText="Product Name" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Unit_Price" HeaderText="Unit Price " HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="In_Hand" HeaderText="In Hand" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Fixed" HeaderText="Fixed" HeaderStyle-BackColor="Azure" />
<asp:BoundField DataField="Status" HeaderText="Status" HeaderStyle-BackColor="Azure" />
<asp:HyperLinkField DataNavigateUrlFields="Prod_Id" DataNavigateUrlFormatString="edit.aspx?Prod_Id={0}" Text="Edit" />
<asp:ButtonField ButtonType="Link" Text="Delete" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
code behind part
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
binddata();
}
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
void binddata()
{
con = new SqlConnection("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
da = new SqlDataAdapter("Select * from Products", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
grdView.DataSource = ds;
grdView.DataBind();
}
protected void grdView_SelectedIndexChanged(object sender, EventArgs e)
{
var P_id = ds.Tables[0].Rows[0]["Prod_Id"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
string qry = "DELETE FROM PRODUCTS WHERE Prod_Id='" +P_id+ "'";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Thanks
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');""CommandArgument='<%#Eval("Prod_Id") %>'>Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int Prod_Id= Convert.ToInt32(e.CommandArgument);
//followed by your code
}
}
You can use LinkButton in GridView
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="delete" title="Delete"
OnClientClick="return confirm('Do you Want to Delete this Record?');"
CommandArgument='<%#Eval("Prod_Id") %>'></asp:LinkButton>
Code Behind
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int P_Id = e.CommandArgument; \\ This will get the Product id in P_Id variable
\\ do your delete code
}
Hi you can get linkbutton using following code:
<asp:TemplateField HeaderText=Quantity>
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="delete" title="Delete"
OnClientClick="return confirm('Do you Want to Delete this Record?');"
CommandArgument='<%#Eval("Prod_Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
And code behind use below code:
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "delete")
{
int P_Id = e.CommandArgument; \\ This will get the Product id in P_Id variable
\\ do your delete code
}
}

direct link to image in database in asp.net

How can we retrieve an image from database with direct link?
I understand that we can get the image as /getImage.aspx?id=1 for instance.
But how can we create a direct link like /image1.jpg ?
you can use URL Rewrite to solve your problem
YOU SHOULD TRY THIS
<asp:GridView ID="GridView1" runat="server" EnableViewState="false"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" />
<asp:BoundField HeaderText="File Name" DataField="FileName" />
<asp:TemplateField HeaderText="File">
<ItemTemplate> <img src="ShowImage.ashx?autoId=<%# Eval("AutoId") %>" alt="<%#
Eval("FileName") %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate> <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Behind Code:
string _connStr =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFiles();
}
}
private void BindFiles()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "SELECT AutoId, FileName, FileContent, Active FROM Files
Order By AutoID ASC";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}

Resources