Why SQLCommandBuider not DELETING? - asp.net

In the following code UPDATE is working but DELETE is not working. When I DELETE row it delete it and GridView1 does not show it but database still has it. customers has PrimaryKey.
using (SqlConnection connection = new SqlConnection(conString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from customers", connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataTable customers = new DataTable();
adapter.Fill(customers);
// code to modify data in DataTable here
customers.Rows.RemoveAt(rowIndex);
GridView1.EditIndex = -1;
GridView1.DataSource = customers;
GridView1.DataBind();
adapter.Update(customers);

You don't want to remove the row from the DataTable but delete it.
The DataRow's DataRowState must be modified to deleted, then the DataAdapter knows that it must delete it in the datasource.
Following will delete it:
customers.Rows(rowIndex).delete();//now DataRow's DataRowState is Deleted
adapter.Update(customers); // now it's actually deleted
Futher informations: MSDN How to: Delete Rows in a DataTable
By the way, following would prevent the DataRow to be deleted, if you've changed your mind:
customers.Rows(rowIndex).RejectChanges();
The RowState will change back to Unchanged.
This works either for the DataRow or for the whole DataTable.

Related

Radtrelist binding

I am trying to bind the simple employee table to Radtreelist but it shoes only columns not data.
source view-->
following is code that i used to bind data to Radtreelist control
void binddata()
{
cn = new
SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
strquery = "select Emp_Id,Emp_Name,Emp_Salary,DeptID from Employee";
da = new SqlDataAdapter(strquery, cn);
dt = new DataTable();
da.Fill(dt);
RadTreeList1.DataSource = dt;
RadTreeList1.DataBind();
}
and table having field Emp_Id,Emp_Name,Emp_Salary,DeptID
so when i run the application it shoes only column of database
You're probably not setting the DataKeyNames and ParentDataKeyNames properties of the RadTreeList
Check the demo here.

asp.net grid view and dataList

I need help with a part of my website I'm coding. I have a listBox_Products which is populated with sqlServerDataSource. When I click on a product, it will display a corresponding picture along a gridview with productPrice and productName. The gridview is databound programmatically in the codebehind, on the indexChange event. I have a button, addToShoppingCart. On the button_Click event, I want to add the item the user chose to the shopping cart (it's on the same page), I have a second gridView, which received the item the user chose and displays it. This is where I'm stuck. I know I can't append to gridview, and I know it has to be databound. My logic is this: get the first item user chooses, add it to a datatable, insert into second gridview. Now if the user chooses another product, same logic, except this time, I would add a new row, and add the new data to the new row, keeping old row as well. Problem is I can't figure out how to do this. I'm not very experienced in datatable.
This is my code behind.
This is my code to get the product from sql server:
Private Sub GetProducts()
Dim TechShopConnectionString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
Dim TechCon As New SqlConnection(TechShopConnectionString)
Dim TechCmd As New SqlCommand()
Dim index As Integer = ListBox_Products.SelectedIndex()
TechCmd.CommandType = CommandType.StoredProcedure
TechCmd.CommandText = "GetAllProductInformationByID"
TechCmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
TechCmd.Connection = TechCon
Try
TechCon.Open()
GridView2.EmptyDataText = "No Records Found"
GridView2.DataSource = TechCmd.ExecuteReader()
GridView2.DataBind()
Catch ex As Exception
Throw ex
Finally
TechCon.Close()
TechCon.Dispose()
End Try
End Sub
This is my code to add item to the second gridview:
Protected Sub Button_AddToCart_Click(sender As Object, e As EventArgs) Handles Button_AddToCart.Click
Dim conn As SqlConnection = Nothing
Dim index As Integer = ListBox_Products.SelectedIndex()
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
conn = New SqlConnection(connString)
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "GetAllProductInformationByID"
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
cmd.Connection = conn
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dr2 As DataRow
dataTableCheckOut.NewRow()
dataTableCheckOut.Load(dr, LoadOption.OverwriteChanges)
GridView_CheckOut.DataSource = dataTableCheckOut
GridView_CheckOut.DataBind()
Catch ex As SqlException
Catch ex As Exception
Finally
conn.Close()
End Try
' Enter code here
As you can see I'm pretty lost. I know the logic is fine, but I cant figure out the code.
Any help would be appreciated.
If you want to keep the information about what is in the users cart from page to page (which you should want to), you should be saving the items in the users cart to the database. If you go to Amazon.Com, add something to your cart, then come back later, even on another compter, you can see the items in your cart, based on your login.
Since you know how to read data from the database, this should be easy for you. Just add the info to this new cart table and read it when you need it. Maybe every page shows the number of items and you just need the count but when viewing the cart of checking out, you need to show all the info.

Load database data into asp.net page

I would like to know how to load data from a database into a asp.net form.
So I use code to get the data via a query "Select * From ... Where ... = ..."
Then I load it into a reader and
While (reader.read)
{ string sProductName = Convert.ToString(reader[1]);
/*
Now I need to display this name and all the other data
(selling price, etc) on the form
But as I do not know how many products there will be it (the form) has to change
as the database information does (more products get added or removed).
*/
}
I do not know how to do that last part. How to make the data found display on screen.
Thanks !
The data I need to display is a the Product Name, the Product Description and the Product Selling Price underneath headings with those names thats all.
For SQL Database,
Take gridview control with id="gridview1" (whatever you like but use same id in code)
SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gridview1.DataSource = ds;
gridview1.DataBind();
SqlConnection sql= new SqlConnection("your data base connection");
SqlCommand cmd = new SqlCommand("select * from your_table_name", sql);
sql.open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Textbox1.Text=dr[0].ToString();
Textbox2.Text=dr[1].ToString();
Textbox3.Text=dr[2].ToString();
......................;
}
con.close();
NOTE:
While working with datareader sql connection must be open.
I use textboxes to show the values.You can use where ever it is necessary .dr[0].ToString(),.dr[1].ToString() .....Contains the values of database table

How to sync Datagridview and datasource when user sorts column?

I have a DataGridview in a windows form project that is directly bound to a Dataset through a SqlDataAdapter. I have one editable column which a user can edit and that works great if the user does not sort the column.
If the user sorts the column the underlying datasource gets out of sync with what the Datagridview is displaying.
What is a standard technique to keep the gridview and datasource in sync when a user sorts it?
Thanks!
As per my understanding auto sorting does not works with DataGridView, for performing sorting you need to sort the datasource and then rebind it to the GridView as shown in code below
private void Sort_DataGrid(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
// Never use Queries like this always use Stored procedures
SqlCommand myCommand = new SqlCommand("SELECT * FROM Categories", myConnection);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds, "Categories");
DataView dv = new DataView(ds.Tables["Categories"]);
if ((numberDiv % 2) == 0)
dv.Sort = e.SortExpression + " " + "ASC";
else
dv.Sort = e.SortExpression + " " + "DESC";
numberDiv++;
myDataGrid.DataSource = dv;
myDataGrid.DataBind();
}
I can't seem to find an event that triggers for clicking on the header to sort a datagridview.

Edited value does not change while updating in website

My scenario is as follows.
I'm using ASP.NET 2.0 and VB.NET.
I have a login page. If I am an existing user, when I log in, my user details are popped in the respective textBoxes. Now I wish to change one of these fields. I edited one and then clicked on the Edit button to update the record. It's not updated but instead it brings the existing value from the text box.
How can I achieve this?
DBCmd.CommandText = "update IOMFNewMember set FirstName=#FirstName,MiddleName=#MiddleName,LastName=#LastNa,Gender=#Gender,DateofBirth=#DateofBirth,MartialStatus=#MartialStatus,DateofWedding=#DateofWedding,Nationality=#Nationality,ResidenceCountry=#ResidenceCountry,DateofJoiningIOMf=#DateofJoiningIOMf,EmailId=#EmailId,mobileno=#mobileno,AtPresent=#AtPresent,familykuwait=#familykuwait,DateofDeath =#DateofDeath where UserName=#Entery and MemberID=#MemberID"
For your requirement you have to run a sql command same as that u are using to populate the textboxes with the user details.
That is supposing you are using this in the login button click event
string strSql="select * from customers where id=" + txtLoginId.Text;
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=new SqlCommand(strSql,con);
DataSet dset=new DataSet();
da.Fill(dset);
con.Close();
You will have to use this in the edit button click event :
string strSql="update EmployeeTable set password = '" + txtPassword.Text + "'";
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlCommand cmd=new SqlCommand(strsql, con);
cmd.ExecuteScalar();
con.Close();
Hope this will clear you confusion.
This is just an example. For a real time situation its advisable to use stored procedures only for any database query.

Resources