Use of SqlCommandBuilder in ASP.NET - asp.net

I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?

Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.

Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.

Related

How to prevent PostBack while clicking button in ASP.NET

The following picture is view of one of my WebForms in project. I am currently facing following problem: I am loading CSV file, the program analyzes it and displays it as a Table. Then, using DropDownLists and Textboxes below, user chooses day, project and hours in order to decrease hours, which have been assigned to the project (imagine project x, which has budget of 100.000$ and has 150h to be burned by workers. Each worker burns his own hours and web admin can see how many hours can be burned and how does the budget look like). When I decrease hours for some day, for example project x, Monday, 8h- the page reloads and all the things, including table, dropdownlists and textboxes are closed and user add project hours for another days.
Please see the code that is responsible for changes in the database and is executed during Submit button click:
private void decreaseProjHours()
{
if (IsPostBack)
{
string nameOfProject = DropDownList1.SelectedValue;
int dayID = DropDownList2.SelectedIndex;
int hours = Convert.ToInt32(TextBox3.Text);
if ((nameOfProject == "") || (dayID > 7 || dayID < 0) || hours < 0)
{
Response.Write("You have entered invalid data in one of the fields!");
return;
}
//decreasing from total hours assigned to project
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WorkTimeDBConnectionString"].ConnectionString);
conn.Open();
string getTotalProjectH = "select hours from projects where project_name='" + nameOfProject + "'";
SqlCommand com = new SqlCommand(getTotalProjectH, conn);
int check = Convert.ToInt32(com.ExecuteScalar().ToString());
if (check - hours < 0)
{
Response.Write("No more hours can be reported for project" + nameOfProject);
conn.Close();
return;
}
else
{
try
{
string tryUpdate = "update projects set hours='" + (check - hours) + "'" + " where project_name='" + nameOfProject + "'";
SqlCommand com1 = new SqlCommand(tryUpdate, conn);
com1.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
conn.Close();
return;
}
}
}
}
Is is the problem with PostBack? I already tried making OnClientClick return false and Button3.Attributes.Add("onclick", "return false;")- the operation of modifying the database fails then and nothing is submitted.
What should I do? Is it really problem with PostBack or something else refreshes my webpage?
EDIT:
Button3.Attributes.Add("onclick", "return false;");
Button3.OnClientClick = "decreaseProjHours(); return false;";
Button3.UseSubmitBehavior = false;
Thanks in advance,
Kokos
You have more or less the correct code in the line
Button3.OnClientClick = "decreaseProjHours(); return false;";
However the problem is that it looks for a javascript function decreaseProjHours(), which I'm assuming you don't have since you have that method on the server side in your code behind. OnClientClick is by definition a client-side handler and so the method needs to be defined on the client side. Since it can't find the javascript function, it fails to execute the next line return false;.
If you need that code to execute first and then return false to prevent postback, you need to put the code in a javascript function instead of in the code-behind. You can then have that fuction either return true or false if you wish, instead of having the additional return statement in the OnClientClick definition.
Note that if you have a server-side click handler defined as well, this won't execute if there is no postback; i.e. the server-side OnClick handler only executes if the client side returns true.

radGrid control displays blank grid after date parameter is changed

I searched SO, google & Telerik forums, but could not find a solution.
I have an existing app (written by a previous developer) that is calling a stored procedure that populates a RadGrid control. It populates fine the first time around.
However, when I change the date parameter, click "search" button, I get a blank RadGrid control. When I click search the second time, the grid is populated. When I walk through the code, I get an error message
Column 'ID' does not belong to table Table.
How can I resolve the issue of having to click search twice to display data ?
My code behind is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
try
{
ViewState["newset"] = null;
CreateDatasource();
this.RadGrid1.DataBind();
this.RadGrid1.CurrentPageIndex = 0;
ViewState["newset"] = "new";
string idex = this.hdnindex.Value;
if (idex != string.Empty)
this.RadGrid1.MasterTableView.Items[int.Parse(idex)].Selected = true;
}
catch (Exception ex) {
this.lblMessage.Text = ex.Message;
}
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
try
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
HyperLink hLink = (HyperLink)item["ViewHyperLink"].Controls[0];
if (hLink != null)
hLink.Attributes.Add("onclick", "selectMe('" + item.ItemIndex + "');");
}
}
catch (Exception ex)
{
this.lblMessage.Text = ex.Message;
}
}
In the code behind above, when this.RadGrid1.DataBind() is called, the code steps into RadGrid1_ItemCreated loops through the if statement a few times, them goes into the if statement, comes out of the function, and then the catch statement of btnSubmit is called, which displays the error message "Column ID does not belong to table Table".
Any ideas on how to resolve this?
Maybe you should try Grid - Simple Data Binding. Also you this thread (RadGrid NeedDataSource Page load) on telerik forum talks in detail about Simple Data binding. I don't know if you are trying to use NeedDataSource, but I have had similar issues before and the Simple Data binding worked perfectly.
That sure sounds like to me you need to call RadGrid1.Rebind() somewhere. Try calling that for your last line in your try block inside btnSubmit_OnClick.
Also, what does this search button do? Does it filter the results based on a date?

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

MySqlDataAdapter failed to retrieve data on the first load

I use MySQL Connector for ASP.NET to retrieve data from my MySQL server. Everything seems to work fine, but just at the first asynchronous postback of my page, MySQLDataAdapter does not fill my DataSet. After a complete refresh the data is succesfully loaded by asynchronous postback.
I try to assign a bigger value to the command timeout, but it does not seem seem to work.
This does not happen locally, only on the production server.
I have checked that the fill does not work by displaying the request string and also by on each async postback (displaying the count() of my DS.table[0].rows).
This is really the fill method not working.
try
{
using (MySqlConnection conn = new MySqlConnection(_connexionString))
{
string requete = "";
DataSet DS = new DataSet();
requete = "SELECT * from MYTABLE";
using (MySqlDataAdapter MSDA = new MySqlDataAdapter(requete, conn))
{
DS.Clear();
MSDA.Fill(DS);
}
conn.Close();
conn.Dispose();
}
}
catch (MySqlException ex)
{
l_error.Text = ex.ToString();
}
Try putting code into Page_Init event too.
did you checked Page.isPostBack property ? may be you are not checking isPostback, properly. it would be helpful,if you share your entire method.
if(!Page.IsPostBack)
{
//load your datasets and data - adapters.
}
After few investigation in code, i found that it not work, in fact an value of request was empty ... so no data return by mysql server, there was session key which was expire...
thx all for your help !

Resources