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.
Related
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
I'm working on radgrid in asp.net.
While doing on ExportToPDF I needs to get each record in separate page.
Currently I'm getting all records in with out any page level to each record.But How can we set each record with in a page level ?
Example : If there are 100 records I should able to get 100 pages in the exported pdf where each record in one page.
Aspx code :
<telerik:RadGrid ID="dlTemplate" runat="server" AutoGenerateColumns="false"
AllowPaging="true">
<GroupingSettings CaseSensitive="false" />
<PagerStyle AlwaysVisible="true" Mode="NextPrevAndNumeric" />
<ExportSettings ExportOnlyData="true" OpenInNewWindow="true"
IgnorePaging="true" FileName="Template">
<Pdf PageTitle="Letter Template" PaperSize="A4" />
<Pdf PageWidth="270mm" PageHeight="297mm" />
</ExportSettings>
<MasterTableView DataKeyNames="Message" TableLayout="Auto" HeaderStyle-
CssClass="title-b14px" ItemStyle-CssClass="txtlable-b13px-normal">
<Columns>
<telerik:GridBoundColumn UniqueName="Message" DataField="Message"
HeaderText="Message">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Aspx.cs code :
protected void print_page(object sender, EventArgs e)
{
try
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("Message", typeof(string));
DataRow dr = dt1.NewRow();
dt1.Rows.Add(dr);
//dt1.Rows[0][0] = lblLable.Text;
string msg = string.Empty;
foreach (GridDataItem row in dlTemplate.Items)
{
for (int i = 0; i < dlTemplate.Columns.Count; i++)
{
var message = row["Message"].Text;
message = Regex.Replace(message, "(<style.+?</style>)|
(<script.+?</script>)", "", RegexOptions.IgnoreCase |
RegexOptions.Singleline);
msg += message + "<br/><hr/>";
}
}
dt1.Rows[0][0] = msg.Remove(msg.Length - 5);
dlTemplate.DataSource = dt1;
dlTemplate.DataBind();
dlTemplate.MasterTableView.ExportToPdf();
}
catch (Exception ex)
{
BLGeneral.LogException(ex);
}
}
update Export Setting
<ExportSettingsExportOnlyData="true"Excel-Format="Html"OpenInNewWindow="true">
<PdfPageHeight="210mm"PageWidth="297mm"DefaultFontFamily="Arial Unicode MS"PageTopMargin="45mm"
BorderStyle="Thin"BorderColor="#666666">
</Pdf>
</ExportSettings>
I have to fill checkboxlist which is within the gridview control.
<asp:GridView ID="gvProject" CssClass="Gridview viewproject-th-col-remov" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvProject_RowDataBound" DataKeyNames="ProjectID" AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkContract" runat="server" Text="Contract" ControlStyle-CssClass="pdf-download-link"OnClick="DownloadFile" CommandArgument='<%# Eval("ProjectId") %>'></asp:LinkButton>
<asp:CheckBoxList ID="chkAdSpace" runat="server"></asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns> </asp:GridView>
Then I have bound the data in checkboxlist like this.
private void BindList(Int32 _id)
{
DataTable dtAdSpace = new DataTable();
dtAdSpace = CommonDataViews.GetAdSpaceSearch(_id);
if (dtAdSpace.Rows.Count > 0)
{
chkAdSpace.DataSource = dtAdSpace;
chkAdSpace.DataTextField = "adspace";
chkAdSpace.DataValueField = "adspace";
chkAdSpace.DataBind();
}
}
But, problem is chkASpace does not accessible int BindList(Int32 _id) or throught the form. Please help me why this is not accessible like LinkButton which I used.
Thanks in advance.
Raja
Retrieve the data to bind in a DataTable.
In GridView_RowDataBound event, Bind the Checkboxlist with the DataTable. Get the Checkboxlist by using FindControl. Like below:
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList cblProject = (CheckBoxList)e.Row.FindControl("chkAdSpace");
cblProject.DataSource = dtAdSpace;
cblProject.DataTextField = "adspace";
cblProject.DataValueField = "adspace";
cblProject.DataBind();
}
}
I think the question was how to do it within ASP.net and not from code behind.
ie: Gridview binds to a datasource, but within the gridview there is a column with a checkboxlist and its own datasource. Using Eval("yourcolumn") tries to bind to the main datasource of the GridView and not the checkboxlist.
Sorry I do not have the answer, as I am trying to determine that as well.
To Check All the ckeckboxes in the list simply iterate through each checkbox to check them.After Databind.
foreach (ListItem listItem in chkAdSpace.Items)
{
listItem.Selected = true;
}
Here is my answer:
The GridView code is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="fprefid" DataValueField="fprefid">
</asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the C# code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList cbl = (CheckBoxList)e.Row.FindControl("CheckBoxList1");
object objTemp = GridView1.DataKeys[e.Row.RowIndex].Value as object;
string id = objTemp.ToString();
SqlConnection con1 = new SqlConnection(constr);
SqlConnection con2 = new SqlConnection(constr);
SqlCommand com1 = new SqlCommand("select prefid from preferences",con1);
if (con1.State == ConnectionState.Closed)
con1.Open();
if (con2.State == ConnectionState.Closed)
con2.Open();
SqlDataReader dreader1 = com1.ExecuteReader();
if(dreader1.HasRows)
{
while(dreader1.Read())
{
SqlCommand com2 = new SqlCommand("select fprefid from person_pref where fpersonid='" + id + "' and fprefid = '" + dreader1["prefid"] + "'", con2);
SqlDataReader dreader2 = com2.ExecuteReader();
ListItem li = new ListItem();
if (dreader2.HasRows)
{
li.Text = dreader1["prefid"].ToString();
li.Selected = true;
}
else
{
li.Text = dreader1["prefid"].ToString();
li.Selected = false;
}
cbl.Items.Add(li);
dreader2.Close();
}
}
}
}
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
}
}
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();
}