Why is my DataSet not populating my GridView - asp.net

I dont know why my data is not showing in my gridview, if i use an sqldatasource with the same query it works.
cmd.Connection = conn
conn.Open()
cmd.CommandText = "SELECT DISTINCT TOP (100) PERCENT dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName, SUM(dbo.tblData_DeviceByDevice.ACDCount) AS Calls, SUM(dbo.tblData_DeviceByDevice.ACDDuration) AS Seconds, dbo.tblConfig_AgentGroup.Name, dbo.tblConfig_Agent.Pkey FROM dbo.tblData_DeviceByDevice INNER JOIN dbo.tblConfig_AgentGroup ON dbo.tblData_DeviceByDevice.FKDevice2 = dbo.tblConfig_AgentGroup.Pkey INNER JOIN dbo.tblConfig_Agent ON dbo.tblData_DeviceByDevice.FKDevice1 = dbo.tblConfig_Agent.Pkey WHERE (dbo.tblData_DeviceByDevice.MidnightStartDate BETWEEN '4/10/2011' AND GETDATE())GROUP BY dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName, dbo.tblConfig_AgentGroup.Name, dbo.tblConfig_Agent.Pkey ORDER BY Seconds, dbo.tblConfig_Agent.FirstName, dbo.tblConfig_Agent.LastName"
da.Fill(ds, "test")
GridView2.DataSource = ds.Tables("test")
GridView2.DataBind()
conn.Close()
UpdatePanel1.Update()

I think you have to review your Dataset filling method....
DataAdapter
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");

Related

Pass datatable as parameter to a stored procedure to perform update

I need pass the whole table to a stored procedure to run a update query.
This is my code:
CREATE TYPE [dbo].[UploadData] AS TABLE
(
[CODE] [varchar](4) NULL,
[SERIALNUMBER] [varchar](20) NULL,
[PRODUCTCODE] [varchar](20) NULL,
[THRESHOLD] [int] NULL
)
This is my stored procedure:
CREATE PROCEDURE sp_UpdateExchangeThreshold
#TableType dbo.UploadData READONLY
UPDATE [dbo].[ExchangeData_20221213]
SET t.Threshold = tbl.THRESHOLD
FROM [dbo].[ExchangeData_20221213] t
INNER JOIN #TableType AS tbl ON t.ProductCode = tbl.PRODUCTCODE
AND t.SerialNumber = tbl.SERIALNUMBER
In my VB.Net code, I have this:
Using sqlCommand As SqlCommand = New SqlCommand()
sqlCommand.Connection = connection
sqlCommand.CommandText = "sp_UpdateExchangeThreshold"
sqlCommand.CommandTimeout = 180
sqlCommand.CommandType = CommandType.StoredProcedure
Dim parameterList As SqlParameter = New SqlParameter("#TableType", SqlDbType.Structured)
parameterList.Value = dataTable
parameterList.Direction = ParameterDirection.Input
sqlCommand.Parameters.Add(parameterList)
sqlCommand.ExecuteNonQuery()
End Using
I'm not able to update the records. Any mistake I made? Please help
Unfortunately, a .NET ADO datatable is NOT a SQL Server table type. They have NOHTING to do with each other. You can use a datatable with Oracle, MySQL, or any server based system. You can even use a access database with a data table.
So, datatable object is platform gnostic (neutral), and thus can't be passed, used as a SQL table type.
However, you don't really have to pass a table back. The REAL question is what do you want to do with this table?
Do you want to edit, or update or insert rows from that table back into the database?
If yes, then use a table adaptor (that's what they are for).
Not only will they do all the dirty work for you, but that table can have updates, deletes, edits and insert/additions.
And with ONE command you can send that WHOLE table + all edit/update/delete/adds in one shot.
Say like this:
Dim rstHotels As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT * FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
' delete first row
rstData.Rows(0).Delete() ' delete first row
rstData.Rows(2).Item("City") = "Zoo" ' edit/modify the 3rd row
Dim OneNewRow As DataRow = rstData.NewRow
OneNewRow("FirstName") = "First Name"
OneNewRow("LastName") = "last Name"
OneNewRow("HotelName") = "My Hotel Name"
OneNewRow("Active") = True
rstData.Rows.Add(OneNewRow)
' now, lets send edits/delete/inserts back to database.
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData)
End Using
End Using
Now, I have the load the table and the update as per above, but they can be done separately.
Edit: Sending the datatable to SQL Server, but not all rows.
' so, lets "send" to the sql database some data
Dim rstData2 As New DataTable
rstData2.Columns.Add("HotelName", GetType(String))
rstData2.Columns.Add("City") ' FYI -- defualt is string
rstData2.Columns.Add("Active", GetType(Boolean))
' lets create 5 test rows of data
For i = 1 To 5
Dim MyNewRow As DataRow = rstData2.NewRow
MyNewRow("HotelName") = "Hotel #" & i
MyNewRow("City") = "City #" & i
MyNewRow("Active") = True ' you MUST include columnes that require deffault value
rstData2.Rows.Add(MyNewRow)
Next
' now send in one shot to database
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT ID, HotelName, City, Active FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData2)
End Using
End Using

How to connect to multiple databases in asp.net using SqlDataReader?

How to connect to multiple databases in asp.net using SqlDataReader?
Assume that I have two databases such as “Product” and “people”. The product database has two tables, let’s say table1 and table 2, while people has two tables, let’s say again table1 and table2.
I want to get some information from Product.table1 and some from people.table2.
I tried with the following code, but unfortunately it does not work:
SqlConnection con1 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Product.mdf;Integrated Security=True");
SqlConnection con2 = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\People.mdf;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select prod_name, prod_price from product_tbl", con1);
SqlCommand cmd2 = new SqlCommand("select std_name from student_tbl", con2);
con1.Open();
con2.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
SqlDataReader dr2 = cmd2.ExecuteReader();
// GridView1.DataSource = How to do it??
GridView1.DataBind();
You can either do it as follow :
Retrieve the result from Product DB in dataset1
Retrieve the result from People DB in dataset2
Use DataSet.Merge Method to merge the two data sets in a single dataset say dsProductPeople
Bind dsProductPeople to the grid
OR you can use following example :
// Assumes that customerConnection is a valid SqlConnection object.
// Assumes that orderConnection is a valid OleDbConnection object.
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);
OleDbDataAdapter ordAdapter = new OleDbDataAdapter(
"SELECT * FROM Orders", orderConnection);
DataSet customerOrders = new DataSet();
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
DataRelation relation = customerOrders.Relations.Add("CustOrders",
customerOrders.Tables["Customers"].Columns["CustomerID"],
customerOrders.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows)
{
Console.WriteLine(pRow["CustomerID"]);
foreach (DataRow cRow in pRow.GetChildRows(relation))
Console.WriteLine("\t" + cRow["OrderID"]);
}

button wont save to database it comes to exception error

i made a asp.net site with 3 textboxes and 1 dropdown list and a save button evvry time i click it, it give back An exception of type 'System.NullReferenceException' occurred in Bon-Temps.dll but was not handled in user code.
it give this error on de code line
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
my question is why??
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BT-1ConnectionString"].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from OpdrachtGever";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "OpdrachtGever");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
drow["Naam"] = TextBox1.Text;
drow["Adres"] = TextBox2.Text;
drow["PostCode"] = TextBox3.Text;
drow["AantalPersonen"] = DropDownList1.SelectedItem;
ds.Tables["OpdrachtGever"].Rows.Add(drow);
da.Update(ds, "OpdrachtGever");
You have named your table as
da.Fill(ds, " OpdrachtGever ");
^ ^
but then you refer to it with
DataRow drow = ds.Tables["OpdrachtGever"].NewRow();
without any spaces.
There is a rogue space also on this line
ds.Tables["OpdrachtGever "].Rows.Add(drow);
^
It is not a good idea to have these spaces in your table name because they are not meaningfull for us (humans) and easy to forget. But, for the indexer of the table collection, a space makes a difference. So, when you pass the name with the wrong or missing spaces, the indexer is not able to find your table and returns null .

SQL OUTPUT Parameter Not Assigning

I have the following SQL Statement written in SQL Server 2008 which isn't returning a value for the OUTPUT Parameter even though there is data in the table. I added static values and ran the query alone and it produced a record so I am not sure if it has something to do with my Stored Procedure or my VB.NET Code.
ALTER Procedure [dbo].[GetGenInfo_Delete01_01_22]
#IDX int,
#FPath varchar(100) OUTPUT
AS
Begin
SELECT #FPath = FilePath FROM GENINFO_E1_01_22 WHERE ID = #IDX
DELETE
FROM GenInfo_E1_01_22
WHERE ID = #IDX
END
My VB Code
Using con As New SqlConnection(connstr)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "GetGenInfo_Delete01_01_22"
cmd.Parameters.Add("IDX", ID)
cmd.Parameters.Add("#FPath", SqlDbType.VarChar, 100)
cmd.Parameters("#FPath").Direction = ParameterDirection.Output
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
An output parameter does not show up in the result set. So you can't read it with ExecuteReader().
You can read it like:
Dim result as String = cmd.Parameters("#FPath").Value

There is already an open DataReader associated with this Command which must be closed first

Dim staffid = TextBox1.Text
Dim conn As New SqlConnection
conn.ConnectionString = SqlDataSource1.ConnectionString
Dim command1 As New SqlCommand("SELECT StaffDetails.StaffID, SUM(HolidayRequests.RequestTotalDays) AS Expr1 FROM HolidayRequests INNER JOIN StaffDetails ON HolidayRequests.Username = StaffDetails.UserName WHERE (StaffDetails.StaffID = staffID) GROUP BY StaffDetails.StaffID, HolidayRequests.ApprovalStatus HAVING (HolidayRequests.ApprovalStatus = N'approved')", conn)
Dim command2 As New SqlCommand()
conn.Open()
Dim rdr As SqlDataReader
rdr = command1.ExecuteReader
Dim UpdateQuery As String
While (rdr.Read())
UpdateQuery = "UPDATE HolidayEntitlement set Holiday_Taken = #Expr1"
command2.Parameters.AddWithValue("#Expr1", rdr("Expr1").ToString())
'run update query
command2.CommandText = UpdateQuery
command2.ExecuteNonQuery()
conn.Close()
End While
The following error:
command2.ExecuteNonQuery: Connection property has not been initialized.
Hi you need to create a second command object. Since you are reading from the same command object you are trying to execute the update statement with.
Furthermore you are closing the connection inside the while-loop. you have to do this afterwards.
Create a second command. In other words, use one cursor for reading, the other for updating.

Resources