I'm noobie to this :)
I'm getting data from SQL Server in the page_load event handler, and that works fine with SqlDataReader.
I also added a DataTable. I want to use the data when selecting a dropdownlist.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string mainconn1 = ConfigurationManager.ConnectionStrings["SqlConnection1"].ConnectionString;
SqlConnection sqlconn1 = new SqlConnection(mainconn1);
string Sqlquery1 = "SELECT p.[Name], m.machineid,md.MachineNumber, md.HostName FROM [db].[dbo].[Machine] m INNER JOIN MachineDevice md ON md.MachineID = m.MachineID INNER JOIN property p ON m.PropertyID = p.PropertyID WHERE ([status] = '1') AND (md.DateTimeRetired IS NULL) ORDER BY md.MachineNumber";
SqlCommand sqlcomm1 = new SqlCommand(Sqlquery1, sqlconn1);
sqlconn1.Open();
SqlDataReader rd1 = sqlcomm1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rd1);
}
}
And this:
protected void Ort_SelectedIndexChanged1(object sender, EventArgs e)
{
if (Ort.SelectedValue == "Stockholm")
{
// while (rd1.read)
// {
// Machine.DataSource = rd1;
// Machine.DataTextField = "MachineNumber";
// Machine.DataValueField = "MachineNumber";
// Machine.DataBind();
// Machine.Items.Insert(0, new ListItem("-Select Machine-", "0"));
// }
}
}
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
Thanks
Sure, say we have a drop down (combo box) of some cities, and when you select the city, we fill out a gird of hotels.
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
you could in some cases "persist" the data, but the cost is just as high as in most cases hitting the database again.
so, yes, it is standard fair to re-pull that data.
example:
this markup:
<h3>Select Hotel city</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="150px" Height="30px"
DataTextField="City"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="GVHotels" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" Width="40%" OnRowDataBound="GVHotels_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" HeaderStyle-Width="120"/>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Province" />
<asp:TemplateField>
<ItemTemplate>
<button runat="server" id="cmdEditBooking"
type="button" class="btn myshadow"
onserverclick="cmdEditBooking_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, we have a combo box (dropdown list) of city to select, and then we display hotels from that city.
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo();
}
void LoadCombo()
{
string strSQL = "SELECT City FROM City ORDER BY City";
SqlCommand cmdSQL = new SqlCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select City", ""));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex >0)
{
string strSQL =
#"SELECT * FROM tblHotelsA
WHERE City = #City
ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.Text;
GVHotels.DataSource = MyRstP(cmdSQL);
GVHotels.DataBind();
}
}
And both of above use this handy helper routine:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, result:
Related
Inward.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="pono" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField SelectText="Update" ShowSelectButton="True" />
<asp:BoundField DataField="pono" HeaderText="pono" ReadOnly="True" SortExpression="pono" />
<asp:BoundField DataField="podate" HeaderText="podate" SortExpression="podate" />
<asp:BoundField DataField="partyname" HeaderText="partyname" SortExpression="partyname" />
<asp:BoundField DataField="flag" HeaderText="flag" SortExpression="flag" />
<asp:BoundField DataField="itemnm" HeaderText="itemnm" SortExpression="itemnm" />
<asp:BoundField DataField="indt" HeaderText="indt" SortExpression="indt" />
<asp:BoundField DataField="qty" HeaderText="qty" SortExpression="qty" />
</Columns>
</asp:GridView>
inward.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string pono = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Update_inward.aspx?pono="+pono);
}
update_inward.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string stcon = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(stcon);
con.Open();
String query = "Select * from maxus_in where pono=" + Request.QueryString["pono"];
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TextBox1.Text = ds.Tables[0].Rows[0]["pono"].ToString();
TextBox2.Text = ds.Tables[0].Rows[0]["podate"].ToString();
TextBox3.Text = ds.Tables[0].Rows[0]["partyname"].ToString();
TextBox4.Text = ds.Tables[0].Rows[0]["itemnm"].ToString();
}
con.Close();
}
How do i transfer this data and display in textboxes in another page??
You can Use Query String or store value in the session and retrieve the value on page load of the next page.
username.Value = Request["username"];
username.Value = Session["username"].toString();
I have the below gridview on a page to display users with a role of "Reviewer". The grid pulls up the records correctly. On the gridview is a "delete" button to remove the Reviewer role. The stored procedure that is called is working correctly when ran manually, but I seem to be missing something on the aspx or codebehind page as while no error is returned, no record is deleted either.
aspx control for gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Current Reviewers" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Reviewers Configured." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc" DataKeyNames="UserId" OnRowDeleting="DeleteRecord">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="Id" ItemStyle-Width="300" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="250" />
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandArgument='<%# Eval("UserId") %>' CommandName="DeleteRecord"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Updated with full code behind:
namespace cs1.Admin
{
public partial class ReviewerMaintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
private void BindDropDownList1()
{
string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = String.Format("SELECT Id as UserId, FirstName + ' ' + LastName As Name from AspNetUsers where Id in(SELECT UserId from AspNetUserRoles where RoleId = 1)");
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Reviewer");
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDropDownList1(); //bindgridview will get the data source and bind it again
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Try to use the OnRowCommand event of the GridView to handle this.
In your Gridview markup:
ensure OnRowCommand="GridView1_RowCommand" is present.
In your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{ /* Set a breakpoint here and make sure:
A.) You are hitting this method
B.) Get value of e.CommandName */
if (e.CommandName == "EditRecord")
{
// Run your edit/update logic here if needed
}
if (e.CommandName == "DeleteRecord")
{
// Delete the record here
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
This ended up being a very simple thing. On the aspx page I had both the OnRowDeleting and CommandName elements set to the same value of "DeleteRecord".
Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully.
I am working with Asp.Net C# and want to take the id of the row with a checkbox from the GridView.
With the code above if is checked the only think i am getting with debug is:
chk: {Text = "" Checked = false}
What i am doing wrong and how i can fix this?
<!-- language: lang-css -->
protected void Page_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
if(!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
string user = Session["user"].ToString();
using (MySqlConnection con2 = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT RouteNo,sender FROM routedoc WHERE Recipient = #user ", con2);
adp.SelectCommand.Parameters.AddWithValue("?user", user);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sender";
DropDownList1.DataValueField = "RouteNo";
DropDownList1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Write(GridView1.SelectedRow.Cells[1].Text);
foreach(GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("box") as CheckBox ;
if (chk.Checked)
{
var id = row.FindControl("RouteNo") as Label;
Response.Write(id.Text);
}
}
}
routedoc.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="routedoc.aspx.cs" Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>page 2<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="136px" >
</asp:DropDownList>
</h1>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Recipient,DocHandle,Sender" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RouteNo" HeaderText="RouteNo" InsertVisible="False" SortExpression="RouteNo" />
<asp:BoundField DataField="Recipient" HeaderText="Recipient" ReadOnly="True" SortExpression="Recipient" />
<asp:BoundField DataField="DocHandle" HeaderText="DocHandle" ReadOnly="True" SortExpression="DocHandle" />
<asp:BoundField DataField="Sender" HeaderText="Sender" ReadOnly="True" SortExpression="Sender" />
<asp:BoundField DataField="TermNo" HeaderText="TermNo" SortExpression="TermNo" />
<asp:BoundField DataField="SentDate" HeaderText="SentDate" SortExpression="SentDate" />
<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate" />
<asp:BoundField DataField="SentTime" HeaderText="SentTime" SortExpression="SentTime" />
<asp:BoundField DataField="DueTime" HeaderText="DueTime" SortExpression="DueTime" />
<asp:BoundField DataField="Action" HeaderText="Action" SortExpression="Action" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="BUDate" HeaderText="BUDate" SortExpression="BUDate" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox ID="Box" runat="server"/>
</ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:imagingConnectionString %>" ProviderName="<%$ ConnectionStrings:imagingConnectionString.ProviderName %>" SelectCommand="SELECT * FROM routedoc "></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Height="43px" OnClick="Button1_Click" Text="DELETE" Width="109px" />
</form>
</body>
</html>
This is caused by the fact that you always bind your GridView1 with data,
even on post-back. This is causing that all check box-es remain unchecked.
Remove grid loading if you are in post-back, and it should work fine.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
BindDropDown();
}
}
If you, however, need to load grid even in post-back, I will tell you a fix for that.
Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// bind data
}
}
This is because, when you click a button, your page will be still refreshed, which means you will bind the same data to gridview again, resulting in unchecked checkboxes. You can check whether the page is loaded by a button click (Page.IsPostBack) or the page is loaded the first time (!Page.IsPostBack), and do your data binding accordingly.
Hope this makes sense!
I have a Gridview on which I have Edit option for editing the Row. I have written the code for Edit and Update but it is not getting updated and the row gets blank. I debugged the code and didn't got to know what was the exact problem. Please see the code for your ref and let me know what is the exact issue:-
Gridview aspx code:
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False"
AllowPaging="true" PageSize="4" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound"
OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id" OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Also see the CS code:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
// DropDownList ddlPostlistcategory = ((DropDownList)(row.Cells[0].Controls[0]));
TextBox txtPostTitle = ((TextBox)(row.Cells[0].Controls[0]));
TextBox txtPostdesc = ((TextBox)(row.Cells[1].Controls[0]));
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
grdPostData.DataBind();
}
}
protected void grdPostData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdPostData.EditIndex = -1;
BindGrid();
}
Edited part of the code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory");
//TextBox title = ((TextBox)(row.Cells[0].Controls[0]));
//TextBox description = ((TextBox)(row.Cells[1].Controls[0]));
TextBox title = (TextBox)row.FindControl("txtPostTitle");
TextBox description = (TextBox)row.FindControl("txtPostdesc");
DropDownList ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_post SET title=#title,description=#description,active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
grdPostData.EditIndex = -1;
grdPostData.DataBind();
}
}
Code Is perfect just small mistake.
Change
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
To
TextBox ddlActive = ((TextBox)(row.Cells[3].Controls[0]));
You want to set value of Active which is 3rd control not 2nd.
If Your control is in TemplateField then you have find control from row
For DropDownList You need to try something like this:
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
Following Line will generate error
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
You need to find this control ddlActiveInactive from grid which you are missing
Don't Use AddWithValue it gives Unexpected Results Sometimes
SOURCE
EDIT:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
string PostTitle = row.Cells[0].Text;
string Postdesc = row.Cells[1].Text;
string Active = row.Cells[2].Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.Add("#Id",SqlDbType.Int).Value=Id;
cmd.Parameters.Add("#title",SqlDbType.Varchar,100).Value=PostTitle ;
cmd.Parameters.Add("#description",SqlDbType.Varchar,200).Value= Postdesc ;
cmd.Parameters.Add("#Active",SqlDbType.Int).Value=Convert.ToInt32(Active);
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
//GET GDATA FROM DATABASE AND BIND TO GRID VIEW
}
}
I'm building a site but there is a problem.
I don't know how I can access that data of grid in which row the button is clicked.
.aspx file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlEntry"
CssClass="style1">
<Columns>
<asp:BoundField DataField="ReordID" HeaderText="ReordID" InsertVisible="False" SortExpression="ReordID"
Visible="False" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="EmailID" HeaderText="EmailID" SortExpression="EmailID" />
<asp:BoundField DataField="Password" HeaderText="Password" SortExpression="Password" />
<asp:TemplateField HeaderText="Delete" SortExpression="Delete">
<ItemTemplate>
<asp:Button Text="Delete" runat="server" OnClick="Grid_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
<asp:SqlDataSource ID="SqlEntry" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Entry]"></asp:SqlDataSource>
.CS file:
protected void Refresh_Click(object sender, EventArgs e)
{
GridView1.DataBind();
resetdata();
}
protected void Submit_Click(object sender, EventArgs e)
{
string str = "INSERT INTO Entry (Name, EmailID, Password) VALUES ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "');";
Connection conn = new Connection(str);
Refresh_Click(sender, e);
}
protected void resetdata()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
protected void Grid_Click(Object sender, EventArgs e)
{
string str = "DELETE FROM Entry WHERE RecordID = #RecordID";
Connection conn = new Connection(str);
GridView1.DataBind();
resetdata();
}
Connection Class:
public Connection(string qry)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = qry;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
How can I delete the data from SQL Server 2005 using this webpage?
What is the problem in the code?
You could attach a CommandArgument and a CommandName to your button that contains the ID -
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument="<%# Eval('ReordID') %>" CommandName="REMOVE" OnClick="Grid_Click" />
</ItemTemplate>
... then add a RowCommand event to the GridView -
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="REMOVE")
{
int orderId = Convert.ToInt32(e.CommandArgument);
//Do Sql Here
}
}