Save button code connecting to database not working in ASP.NET - asp.net

I am trying to submit filledin information in the form to the database. I have done the below mentioned coding for the save button. When I click on the save button to save the information, I am getting an error. I need it to be done and for the same need help from the geeks around here.
COde for SAVE button data from database
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager
.ConnectionString("welcome").ConnectionString;
SqlConnection con=new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(#ah,#Ap,#qe)",con);
cmd.CommandType = CommandType.Text;
cmd.Parameter.Addwithvalue("#ah", TextBox1.Text.Trim());
cmd.Parameter.Addwithvalue("#ap", TextBox2.Text.Trim());
cmd.Parameter.Addwithvalue("#qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Check the error in the image below:

You are missing an 's' from the ConnectionStrings indexed property. Once you fix that error, however, you will also find you are missing more 's' from the SqlCommand.Parameters property.
To reveal these issues, open Properties of your code-behind file, and choose Build Action of Compile. (Also, I can see from your image that it looks like your project is setup as a Web Site rather than a Web Application; if possible, look into converting this over to a Web Application, as it offers a number of benefits.)
Once you get your syntax corrected, then you should change your code so that the update is invoked through the button click handler, rather than on page load.
In your markup code in the aspx:
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
In your code-behind:
protected void btnSave_Click(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["welcome"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(#ah,#Ap,#qe)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ah", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#ap", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
}
}
Note that I have moved the code into the button click event handler, and out of the Page_Load. The Load event handler should only be used for initialization items needed unconditionally on the execution path of the page (i.e., regardless of whatever button was clicked on the page), and should look something like the following:
protected void Page_Load(object sender, EventArgs e)
{
// Code to run every time the page is created, both initially and on postback
if (IsPostBack)
{
// Code to run every time the page is posted back (any submit event)
}
else
{
// Code to run on the initial creation of the page
}
}

Related

CheckedItems.Count Always Returns a Value of Zero (0)

I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback

Issue regarding implementing SQL Dependency in Application_Start event

i through i will call SQL Dependency related code Application_Start event and my objective will be completed. my scenario is i have a routine in my web application which i invoke manually just clicking on a button when data updated in sql server table. i was told to make this process automated.
so i go through couple of article on SQL Dependency and through i can make my manual process automated by SQL Dependency because we can monitor table change by SQL Dependency and SQL Dependency can notify us when change done.
please see my code
protected void Application_Start(Object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Stop(connectionString);
System.Data.SqlClient.SqlDependency.Start(connectionString);
RegisterNotification();
}
static SqlDependency dep;
private static void RegisterNotification()
{
string tmpdata = "";
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ActivityDate FROM [bba-reman].ContentChangeLog";
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(OnDataChange);
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
tmpdata = dr[0].ToString();
}
}
}
dr.Dispose();
cmd.Dispose();
}
}
finally
{
//SqlDependency.Stop(connStr);
}
}
static void OnDataChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dep = sender as SqlDependency;
dep.OnChange -= new OnChangeEventHandler(OnDataChange);
SiteSearch.CreateIndex(false);
RegisterNotification();
}
protected void Application_End(Object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Stop(connectionString);
}
the above code was running fine but i faced a good problem. suppose no visitor is visiting our web site and at the same time if some one change sql data by a win apps then i saw OnDataChange() event is not firing but if at least one visitor is with our site then OnDataChange() event is firing properly.
may be this is default nature of asp.net engine. i could use SQL Dependency in win service or in winform apps but i have some constrain because the routine which i am calling after detection of data change in db that is in our web application.
So please guide me what i can do as a result OnDataChange() event should always fire if no visitor is visiting our web site.
thanks

how to reload repeater on button click in asp.net

I have a repeater on my page being populated on page load
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
And then I have a section to add a post. What I want it to do is when the user presses add, it reloads the page and displays the updated repeater. However it's not doing this
Everyone has said just reload the databind, except that isn't working as the original databind is in the page load, and the new databind is in a protected void button click.
Can anyone tell me how to do this, or do I just need to place ALL the connection, datasource ad databind info in the button click code?
you can create a function that can be call everytime Button click event fire
Private void BindRepeater()
{
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
}
Protected Button_Click(object as sender , EventArgs e)
{
//call the function to populate the repeater with the updated records
this.BindRepeater();
}
you can resolve it like this . create a method
private void Bind()
{
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
}
now you can use it anywhere on the page where you need to reload the repeater.

Fields not changing in Formview when moving Pagination

I have a formview that on page load makes a call to a sql server and retrieves 5 records which I want the formview to paginate though.
I have sucessfully connected to the db, filled a dataset, and returned data when the web page renders. The problem is that when I move to a new page, the data does not change in the databound field.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
conn = new SqlConnection(connstr);
ds = new DataSet();
da = new SqlDataAdapter("call to stored proc", conn);
try
{
conn.Open();
da.Fill(ds, "m");
FormView1.DataSource = ds;
FormView1.DataKeyNames = new string[] { "PropKey" };
FormView1.DataBind();
}
catch (Exception ex)
{
Result = ex.Message;
}
finally
{
conn.Close();
}
}
Next when the paginate buttons are clicked I have this:
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
}
Please help,
Thanks
You will need to bind the data to the FormView just after setting the new page index like below.
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
BindFormViewData();
}
This is required because the FormView only displays the data for the active record and does not store any other records from the datasource, so upon change of the page index, the datasource is required to be bound again. See: Paging in a FormView Web Server Control
From the above link:
If the FormView control is bound to a data source control, or to any
data structure that implements the ICollection interface (including
datasets), the control gets all the records from the data source,
displays the record for the current page, and discards the rest. When
the user moves to another page, the FormView control repeats the
process, displaying a different record.
Hope this helps.

Response.Redirect causes IsPostBack to be true

I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen?
The page is a custom page in Community Server. Here is the basic code:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// Code removed for testing.
Response.Clear();
Response.Redirect("ApproveResidents.aspx", true);
Response.End();
}
A Response.Redirect will trigger an HTTP GET from the browser. As no data is posted, IsPostBack is false. You have something else going on.
I'd suggest firing up Fiddler and looking at the sequence of requests. It should look something like:
Client: HTTP POST (button click)
Server: HTTP 302 (Redirect)
Client: HTTP GET
Server: HTTP 200 (Writes page)
I suggest this as a better solution to your problem than attempting to redirect from the browser.
protected void Page_Load( object sender, EventArgs e )
{
if (!IsPosBack) {
BuildData();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// do your stuff and clear any some controls, maybe
BuildData();
}
private void BuildData()
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
Sorry, it was an id-10-t error. My event handler wasn't getting called at all. The page had EnableViewState="false". Once I changed that to true it worked.
I also took tvanfosson suggestion. This allows me to display a confirmation message. I can easily check to see if the action has already been taken and safely ignore it. Since I'm likely the only one to ever see this screen, I'm not too concerned with usability.
Response.Redirect(url,true);
this worked for me.
The page is posted back , that is why you're getting it as true. make sure it is false.

Resources