Why delete command is not executing from c#? - c#

Please check the following code:
protected void Button2_Click(object sender, EventArgs e)
{
string y = foredidel.Text;
try
{
using (var sc = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM fixap WHERE Id = #word";
cmd.Parameters.AddWithValue("#word", y);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.Write("Error");
}
}
When the button is clicked, the specified row should be deleted, but it's not doing anything!
Is there something wrong in my code?

My code was working along with some javascript, so it was like....
onclick give id's value to innerHtml of <asp:Label>.
Then take that value to the variable y in C#(you can check my question for
that variable).
Now as it was runat='server', so I used it to concatenate with my
SqlCommand("#word", y).
I don't know if it was a problem of <asp:Label>, but when I changed it to <asp:TextBox> it worked successfully!
So, answer is just to change <asp:Label> to <asp:TextBox> and according to 1st point change innerHTML to value, and it worked!

Related

Saving Gridview Data To Database

I am having a Gridview which i want to save in my another table
My Code is
protected void upload_Click(object sender, EventArgs e)
{
string query1 = "INSERT INTO tbl_Pre_Y1_Bus1 (CRITICAL,SPECIFICATION, [1],[2],[3],[4],[5],TMLCAL) VALUES (#CRITICAL, #SPECIFICATION, #[1], #[2], #[3], #[4], #[5], #TMLCAL)";
foreach (GridViewRow row in GridView2.Rows)
{
using (SqlCommand cmd = new SqlCommand(query1))
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#CRITICAL", row.Cells[0].ToString());
cmd.Parameters.AddWithValue("#SPECIFICATION", row.Cells[1].ToString());
cmd.Parameters.AddWithValue("#[1]", row.Cells[2].ToString());
cmd.Parameters.AddWithValue("#[2]", row.Cells[3].ToString());
cmd.Parameters.AddWithValue("#[3]", row.Cells[4].ToString());
cmd.Parameters.AddWithValue("#[4]", row.Cells[5].ToString());
cmd.Parameters.AddWithValue("#[5]", row.Cells[6].ToString());
cmd.Parameters.AddWithValue("#TMLCAL",row.Cells[7].ToString());
con.Open(); //here i am having an respected error
cmd.ExecuteNonQuery();
con.Close();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
My error is "Object reference not set to an instance of an object."
help me to resolve this
Replace .ToString() with Convert.ToString as shown below. It will handle blank as well as null value. Then you can check why the value is coming null. You also need to add .Text as shown below.
cmd.Parameters.AddWithValue("#CRITICAL", Convert.ToString(row.Cells[0].Text));
cmd.Parameters.AddWithValue("#SPECIFICATION", Convert.ToString(row.Cells[1].Text));
Before calling .ToString() make sure that your object is not null, Also to read cell text you must put .Text
Something like this :
if (row.Cells[0] != null && !string.IsNullOrEmpty(row.Cells[0].Text)) {
cmd.Parameters.AddWithValue("#CRITICAL", row.Cells[0].Text.ToString());
} else {
// Handle it
}

Why is my GridView Rows.Count zero in my RowDeleting and RowUpdating Events?

I have a simple GridView binding to a table in my database.
Everything looks good until I try to delete or update a row.
I get a System.ArgumentOutOfRangeException because "Index was out of range. Must be non-negative and less than the size of the collection."
After analyzing the output of my debugging I realized that my GridView had 0 rows in my rowDeleting and rowUpdating methods. This is the code in one of the methods:
protected void gvTermene_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.RowIndex); //result is 3, for example
System.Diagnostics.Debug.WriteLine(gvTermene.Rows.Count.ToString()); //result is always 0
GridViewRow gvRow = (GridViewRow)gvTermene.Rows[e.RowIndex];
HiddenField hfID = (HiddenField)gvRow.FindControl("IDDoc");
var connectionFromConfiguration = WebConfigurationManager.ConnectionStrings["MsSql Connection"];
using (SqlConnection dbConnection = new SqlConnection(connectionFromConfiguration.ConnectionString))
{
try
{
dbConnection.Open();
string sql = string.Format("DELETE FROM TermenDocumente WHERE IDDocument={0}", hfID.Value);
SqlCommand command = new SqlCommand(sql, dbConnection);
command.ExecuteNonQuery();
gvTermene.EditIndex = -1;
bindDataToGridView();
}
catch (Exception exc)
{
ltError.Text = exc.Message;
}
finally
{
dbConnection.Dispose();
}
}
}
What may the problem be?
Thank you in advance!
My first guess here is that you are changing the view of the page when you enter this event called gvTermene_RowDeleting. Is this event doing a postback on your webpage. If it is, then you're probably losing the locally stored data that you pulled in from the initial SELECT statement you have placed somewhere else. I believe your best bet is to try to fit the statement that gives you gvTermene somewhere into your page_Load event. You can get creative with this by calling other functions from the page Load that will have filters for your search criteria, etc.

Refreshing ListBox Database values on database Update C#

So i have read this question a few times somewhere else but after reading all those question i still have a working solution for it.
The problem is that i am populating a ListBox with Access Database information which you can see below:
private void FinancienData_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Betaald where Maand='Januari'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
listBox4.Items.Add(reader["Autoverzekering"].ToString());
listBox4.Items.Add(reader["Brabant Water"].ToString());
listBox4.Items.Add(reader["Eigen Risico Nicolas"].ToString());
listBox4.Items.Add(reader["Essent"].ToString());
listBox4.Items.Add(reader["Extra"].ToString());
listBox4.Items.Add(reader["Gemeenschappelijke Heffingen"].ToString());
listBox4.Items.Add(reader["Huur"].ToString());
listBox4.Items.Add(reader["Reiskosten Nicolas"].ToString());
listBox4.Items.Add(reader["RKDVC"].ToString());
listBox4.Items.Add(reader["Telefoonrekening Nicolas"].ToString());
listBox4.Items.Add(reader["Telefoonrekening Wendy"].ToString());
listBox4.Items.Add(reader["Woonverzekering"].ToString());
listBox4.Items.Add(reader["Ziggo"].ToString());
listBox4.Items.Add(reader["Zorgverzekering Nicolas"].ToString());
listBox4.Items.Add(reader["Zorgverzekering Wendy"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
This all works fine, BUT there is also a way which a user can update the database values. This is being done as follow:
private void button1_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Betaald set Autoverzekering='JA'";
command.CommandText = query;
command.ExecuteNonQuery(); //is nu non-query omdat je data insert
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
This update works, the value is being changed in the database. Though the problem is that the value wont update in the ListBox where it is displayed... I need to find an easy way that when the user presses that button, it wont only update in the Access database but also in the ListBox (without having to restart the entire form).
Already try'd multiple things i read about (listBox4.DataSource, ListBox RefreshItems, etc. ) but for some reason i cant get it to work (probably because im quite new to C# and .NET).
Could anyone help me out?
Thanks in advance!
In your private void FinancienData_Load method, you don't bind your database set to your listbox, but instead you are reading the rows from a table, adding ListBoxItems containing the row results to your listbox. This is mainly why the listBox4.DataSource binding doesn't work.
To make the update work, I'd recommend refactoring the code a little: How about putting the code that loads the values from the database into its own method, e.g. void LoadDataFromDb() . Once done, you can simply call this method after you updated the values. The method will then fetch the updated values from the database table and fill the listBox again. Don't forget to add listBox4.Items.Clear() to your LoadDataFromDb() method, otherwise you'll continously add new items to the listBox, instead of "refreshing" items.

Gridview rebind data with new parameters

OK, so I need to change the values stored in my gridview based on input from user.
I used to filter it 100% with javascript, but it turns out that it needs to be paged, so that wont work. Instead, I have to call on the datasource again, but with parameters from the textbox.
I've figured out that I must call a function in code behind and from there call DataBind(), but I dont even know where to start. Please help
I know that I ought to post some code to show that I've made an effort, but I really dont have anything to show. i guess it would be something along these lines?:
protected void ReBind(string sParameter)
{
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}
But obviously I'm fumbling in the dark here.
Take a update button
Write method for update function
public int update_method(string ParameterName)
{
module c = new module();
c.DB_Connection();
int i;
string QRY = "UPDATE TableName SET Parameter_Name='" + ParameterName + "' WHERE Parameter_Name='" + ParameterName + "'";
SqlCommand CMD = new SqlCommand(QRY, c.con);
i = CMD.ExecuteNonQuery();
return i;
}
on button click
protected void ButtonUpdate_Click1(object sender, EventArgs e)
{
update_method(ParameterNametxt.Text);
}
update_method(farm, common_obj);
Turns out that this worked out fine:
protected void ReBind(String sParameter)
{
SqlDataSource.SelectParameters.Remove(SqlDataSource.SelectParameters["parameterName"]);
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}

how to write sql query from one page to another

I am currently working on my first website. The problem I have encountered is the following: I have created a paged titled "CustomerList" that obviously list customers from an sql server DB. I have made the records clickable without using the select button that is included in the GridView. When I click a record, it takes me to my desired page. However, I can't seem to find a way to write an sql query from that click event to my desired page. The following is my code for the click event:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
if (row.RowIndex == 0)
{
Response.Redirect("UsageHistoryPage.aspx? EntityID="
+ row.Cells[0].Text);
}
}
As you can see, when I click an index, I go to the "UsageHistoryPage". I've also added row.cells.[0] to take that data and write it to the UsageHistoryPage, which in my case, would be the customers name at the top of the page. Can someone please help me with this? Does anyone have a good tutorial link? thanks.
You can try with this code - Add this code on your UsageHistoryPage
var input = Response.QueryString["EntityId"];
var connectionString = "...";
var queryString = "SELECT Name FROM TABLE WHERE COLUMN=#EntityId";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
using(var command = new SqlCommand(queryString, connection))
{
Command.Parameters.AddWithValue("#EntityId",input)
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Response.Write(String.Format("For Rick Your Name is here{0}", reader[0]));
}
}
}
#Rick you may want to look at how to check if a row is selected for example you don't need the for loop but in my case example need to check if RowIndex is = 1 or > 0 not ==0
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
What you need to do is something like this to make sure that a Row has been selected
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewRow row = GridView1.SelectedRow;
if (this.row.SelectedRows.Count == 1)
{
Response.Redirect("UsageHistoryPage.aspx?EntityID=" + row.SelectedRows[0].Cells[0].ToString());
}
}
If you want to have the Customer's name show up, on the Page Load of the UsageHistorPage.aspx add this code
String strCustName = Request.QueryString["EntityID1"];
this.Page.Title = strCustName;
try something like that.. please let someone here know if any of the ideas are working for you.

Categories