protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 20; i++)
{
DataRow MyRow = DT.NewRow();
MyRow["Col1"] = i;
DT.Rows.Add(MyRow);
}
}
}
For one reason or the other. if I click the button I get the message that Col1 dus not make part of the table TEST. It turns out that there are no columns added to the table. altroug the code in the page load part has been run. I suppose I have to do something with the session state to make my DataTable persistent, but I have no idea what. Can somebody help me out?
Filling a DataTable from SqlQuery : If SqlQuery returns some null values problem ocurrs with DataTable. Is it possible using DataTable with some null values in it? Thanks
Not sure where to post this question so if you can answer this or have a better forum suggestion, please advise:
I have two tables.
Table USACITY has 100 cities with Latitude and Longitude data (Fields=CITY,CITYLAT,CITYLONG). T
Table USAFAC has 12000 facilities with Latitude and Longitude data (Fields=FAC,FACLAT,FACLONG).
I have an expression that I can use to calculate the distance between any city and facility. The resulting field in the view will be DISTANCE.
Resulting view will include CITY, CITYLAT, CITYLONG, FAC, FACLAT, FACLONG, DISTANCE.
The total possible combinations are 1,200,000 however, the dataset that I am interested in will only include city-facility combinations within 150 miles of each other.
I have built 12 databases in Access that I am now in the process of converting to SQL so I am on a rapid learning curve. Any solutions should include code and instructions on creating the view.
I need to construct a stored procedure that will accept a set of comma seperated numbers. What I would like to do is something like this
create procedure shopping_cart(@contents as varchar) as select dvd_title from movie_dvd where dvd_detail_id in (@contents)
dvd_detail_id is defined as int in the table. The problem is if I declare @contents as varchar, the procedure only recognizes the first number and ignores the others. Does anyone know how to get around this?
I have two tables, both with phone numbers and call times.
one is for incoming calls, one for outgoing calls.
I need to find all phone numbers from the incoming calls table where the number of calls exceeds 100 within the last 30 days, where the last call was within the last 15 mins, and where the number does Not exist in the outgoing call table within the last 30 days.
so far I have this... (call record is the incoming, callout is the outgoin)
I believe this is giving me all records in the call record table that are within the last month, and not in the outgoing call table OR have not ben called within the last month..
SELECT cr.cli,min(cr.starttime)as "first call",max(cr.starttime)as "last call",count(cr.cli) as "number of calls" FROM callrecord cr LEFT JOIN callout co ON cr.cli = co.cli where (co.cli is null or datediff(dy,co.calltime,getdate())>30 ) and datediff(dy,cr.starttime,getdate())>30 group by cr.cli order by cr.cli
i need to add in the 15 minute call check, and also only return those with a count of > 100
Hi,I am constructing a Message (Body) for sending our Emails. It is around3000 characters long. But for whatever reason, the last line seems tobe broken with a "!" exclamatory mark in it, which results indisplaying the constructed image path as a broken one.How to resolve this ?. Thanks.Regards,Karthick
Hi friends,please help me in selecting values from the tablethe record is as follows:Id HomePhone WorkPhone Mobile Email20 2323223 323232232 Join Bytes!i have to select values as follows.Id DeviceType DeviceInfo20 HomePhone, Mobile, Email 2323223, 323232232, Join Bytes!the one solution is:select'HomePhone, Mobile, Email' AS DeviceTypeHomePhone + ',' + WorkPhone + ',' + MobilePhone + ',' + Email ASDeviceInfofrom table where Id = 20but here the work phone number is not available so that informationhas to be truncated...Thanks in AdvanceArunkumar.D
Hi i have a page in which stock can be allocated, there are two boxes which have a product serial number start range and a product serial number end range, when these boxes are filled the "allocate" button is then clicked and the product will then be allocated the serial numbers. What i want to happen is that when the start and end ranges have been entered into the text boxes it will fail if any number within the range has already been allocated previously. E.g
Start Range
End Range
So lets say in the start range text box 15 is entered and in the end range 25 is entered, however 18 has already been allocated previously, this will then bring up a message saying please select another range; I have done the following so far;private void ValidateRange() { //String strSql;SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["strConnectionString"]); String strSql = "SELECT SqlCommand dbCommand4 = new SqlCommand(strSql, conn); dbCommand4.Parameters.Add("@Start_RangeID", txt_Start_Range.Text);dbCommand4.Parameters.Add("@End_RangeID", txt_End_Range.Text); dbCommand4.Connection = conn; conn.Open();SqlDataReader myDataReader = dbCommand4.ExecuteReader(); myDataReader.Read();if (txt_Start_Range.Text == Convert.ToString(myDataReader["Serial_No"])) {lblRange.Text = "Please enter a different range a portion of the selected values have already been allocated"; //Response.Redirect("Selectedfilm.aspx"); } else {Allocate(true); }
conn.Close();
}
My problem is constructing the select statement, thanks.
Hi matesI am getting the following error "Invalid object name 't1'.Invalid object name 'relT1T2'." from this line of code " String SQLREL = "SELECT t1.SubCategory2Name, t1.CityName, SubCategory2Name,relT1T2.N FROM " + "t1 INNER JOIN relT1T2 ON t1.PKSUBCAT2ID = relT1T2.FKSUBCAT2ID";"i am basically using datarelation and the relation is working fine and is showing all the data for the parent and child tables but while constructing sql i get above mentioned error.can some one pls help me out. the full code is given below: DataColumn parentCol; DataColumn childCol; parentCol = ds11.Tables["t1"].Columns["PKSUBCAT2ID"]; childCol = ds11.Tables["t2"].Columns["FKSUBCAT2ID"];DataRelation relT1T2; relT1T2 = new DataRelation("T1T2", parentCol, childCol); ds11.Relations.Add(relT1T2); Response.Write(ds11.Tables["t1"].Rows.Count); foreach (DataRow rowParent in ds11.Tables["t1"].Rows) { foreach (DataRow rowChild in rowParent.GetChildRows(relT1T2)) { Response.Write(ds11.Tables["t1"].Rows.Count);//test code DataView dv1 = ds11.Tables["t1"].DefaultView; String SQLREL = "SELECT t1.SubCategory2Name, t1.CityName, SubCategory2Name,relT1T2.N FROM " + "t1 INNER JOIN relT1T2 ON t1.PKSUBCAT2ID = relT1T2.FKSUBCAT2ID"; DataSet ds77 = new DataSet(); SqlConnection cn77 = new SqlConnection(CONN1); cn77.Open(); SqlDataAdapter da77 = new SqlDataAdapter(SQLREL, cn77); da77.Fill(ds77); DataList1.DataSource = ds77.Tables[0].DefaultView; DataList1.DataBind(); cn77.Close();
Hi! I'm trying to put together some reports for an attorney's office. I'm having trouble constructing this query. What I'm doing is querying for defendants who do not have a particular charge against them.
DCharge ------------------------------- VBKey ChargeNum 1 27 2 19 3 20 3 21 etc.. Since both tables are linked via VBKey, I joined them together and this is where I got stuck.
I tried using HAVING ChargeNum<>21 but it would still return a result b/c VBkey=3 has two charges against him. So, when do my queries, I'm still getting individuals who have multiple charges. I tried doing this with SELECT DISTINCT but it would still give me results from people with 3 or more charges. I'm lost at how to complete this query. Any help will be greatly appreciated! Thank you!
Hi I am trying to use the results of a datatable as an input to a ne SQL statement. The datatable is created and populted by the source below after previously creating MyLookupCommand MyLookupReader = MyLookupCommand.ExecuteReader(CommandBehavior.CloseConnection) Dim Mydatatable = New DataTable() Mydatatable.Load(MyLookupReader)
I now create a new SQL string allong the lines of SELECT tableA.field1 FROM TableA INNERJOIN Mydatatable ON tableA.field2 = Mydatatable.Filed9 However I get the following error Invalid object name 'Mydatatable'. Any suggestions on how to resolve this.
possibley of interest is that I would have like to have done this in 1 SQL but the results in Mydatatable are from a SELECT DISTINCT and Field1 is a text filed that can't be used in a DISTINCT statement, hence using two statements. Many thanks in advance
Hi, I'm wondering if this is possible. I want to use a datatable as a parameter in my SQL query. The error I am getting is "No mapping exists from object type System.Data.DataColumn to a known managed provider native type." Any help is appreciated. Here is the code. Private Function GetAvailableTutors(ByVal qualifiedTutorsDataSet As DataTable) As DataTable Dim TutorAvailabilityDataTable As DataTable = New DataTable() Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ASC_Schedule").ConnectionString) Dim myCommand As SqlCommand = _ New SqlCommand("SELECT TutorID, TimeIndex FROM T_Hours WHERE SessionID > 0 AND TutorID IN (@TutorList) AND DateDropped > GetDATE() ORDER By T_QualifiedTutors.TutorID", myConnection) myCommand.Parameters.AddWithValue("@TutorList", qualifiedTutorsDataSet.Columns.Item("TutorID")) Dim myDataAdapter3 As SqlDataAdapter = New SqlDataAdapter() myDataAdapter3.SelectCommand = myCommand myDataAdapter3.Fill(TutorAvailabilityDataTable) Return TutorAvailabilityDataTable
the usual way to bid a gridview is to data soursce is there a way to do the folowing , creat a data table from the gridview shown valus " currunt page "
Is the merge method, what will work in this case ? I have two datatables with the exact same structure. How can I append the rows from table 2 onto the bottom of table 1 ? Is looping through the rows collection the only way ?
Hi,Is it possible to store data that is retrieved by SqlDataSource in a... let's say... DataTable? I mean, If I dragged and dropped a GridView and an SqlDataSource and then I set up those controls in page designer in Visual Studio, is it possible at some time later to retrieve the data retrieved by the SqlDataSource and then store the data in a DataTable?Best regards,Haris
hai This is rameshi had a small doubt in this public DataTable GetStatelist() { DataTable returnValue = null; SqlCommand selcommand = new SqlCommand(); selcommand.CommandType = CommandType.Text; selcommand.CommandText = "select * from USER_MASTER"; selcommand.Connection = _connectionobject; try { _connectionobject.Open(); DataSet ds = new DataSet(); SqlDataAdapter ada = new SqlDataAdapter(selcommand); ada.Fill(ds); _connectionobject.Close(); return returnValue; ; } catch (Exception exception) { if (_connectionobject.State == ConnectionState.Open) { _connectionobject.Close(); } throw new Exception(exception.Message); } if (_connectionobject.State == ConnectionState.Open) { _connectionobject.Close(); } return returnValue; ; } after compiling its show the return value is nullwhat is error in my codinghow i can return the value to the corresponding function if (!IsPostBack) { GridView1.DataSource=database.GetStatelist(); GridView1.DataBind(); } i am waiting for the result
I am fetching records from a table and putting in a datatable using the "sqlda.fill(datatable)" when i see the datable in "data visualizer" i find no rows. It is confused eventhough it does not throw any error
I have a table containing prices. This table will be queried very often to provide quotes for clients.So to ease the burden on the server I want to cache the table and then just query the cached version.However it seems that I can only cache the table as a datatable. This means I have to query the datatable to get the prices for each quote.I'm not sure how to query a datatable. Is ther syntax similar to querying a SQL table?In fact is this best way to go about things?Any help would be appreciated.G
In my appllication, i am having a DataTable... For that DataTable i have to write a query for a expression... This epression is more of mathematical expression type. Here is the sample expression-
How i can write a query for such a equation...? Is it possible to use logical & mathematical operator in the equation & to write a query for this type of equation... Is there is any good article on this...
I have the following: Dim ResourceAdapter As New ResourcesTableAdapters.ResourcesTableAdapter Dim dF As Data.DataTable = ResourceAdapter.GetDataByDistinct Dim numRows = dF.Rows.Count Dim dS As Data.DataTable = ResourceAdapter.CountQuery Dim sumRows = dS.Rows.Count DataList1.DataSource = dF DataList1.DataBind() LblCount.Text = numRows LblSum.Text = sumRows numRows is the number of records in a particular category. CountQuery is a method that returns the total number of records in all the categories. I don't know how to get the result of that query, the code line in bold isn't right. How do I get this number?Diane
I'm trying this code but nothing is being displayedSqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["STRING_CON"]); SqlDataAdapter da = new SqlDataAdapter("my_sproc", conn);DataTable dt = new DataTable(); DataRow dr; //Adding the columns to the datatabledt.Columns.Add("CategoryIdIn"); dt.Columns.Add("CategoryNameVc");foreach (DataGridItem item in gd_freq.Items) { dr = dt.NewRow(); dr[0] = item.Cells[0].Text; dr[1] = item.Cells[1].Text; dt.Rows.Add(dr); }//ForEach da.Fill(dt); gd_freq.DataSource = dt; gd_freq.DataBind();
Can you use a DataTable to update an SQL Table and can it be done in a batch UPDATE as opposed to incrementing through every row using a stored procedure similar to UPDATE SQLTable SET Position = @Position WHERE ID = @ID?
I'm trying to use the SQL Bulk copy class to bulk import from a text file.I'm getting the following error: Line 24: bulkCopy.WriteToServer(CreateDataTableFromFile()); System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) I've even tried to allow remote connections thro pipes and restarted the database engine but to no avail. Any inputs/suggestions?
I am quite new to ASP.net 2.0. I have had plenty of experience using ADO.net in standard windows applications. In my app I am opening a connection to an SQL database and I am creating a DataTable without a DataSet: Shared m_cnADONetConnection As New System.Data.SqlClient.SqlConnection Shared m_daDataAdapter As System.Data.SqlClient.SqlDataAdapter Shared m_rowPosition As Integer Shared m_dtContacts As New System.Data.DataTable I am initializing everything and filling my DataTable when the Page first Loads if it isnt a postback.Protected Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Form1.Load If Not Page.IsPostBack Then m_rowPosition = 0 m_cnADONetConnection.ConnectionString = "Data Source=.SQLEXPRESS;AttachDbFilename=C:First ASP DatabaseApp_DataMyFirstDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" m_cnADONetConnection.Open()m_daDataAdapter = New System.Data.SqlClient.SqlDataAdapter("Select * From Books", m_cnADONetConnection)m_cbRefillCommand = New System.Data.SqlClient.SqlCommand m_daDataAdapter.Fill(m_dtContacts) Me.ShowCurrentRecord() End IfEnd Sub The Me.ShowCurrentRecord Sub assigns the values of the current record(row) in the DataTable via (m_rowPosition) to TextBox controls on the form: I also have record navigation buttons on my form: << < > >> Moving me from record to record (row to row) by incrementing or decrementing m_rowPosition All is good! I am able navigate the DataTable and the textboxes change their text properties accordingly from record to record. The only other control on my form is a button which I'm coding its click event to save changes that I made to the current row (record) by changing the values in the textboxes then clicking save. Here is my code:Protected Sub ButtonSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonSave.Click If m_dtContacts.Rows.Count <> 0 Then m_dtContacts.Rows(m_rowPosition).BeginEdit()m_dtContacts.Rows(m_rowPosition)("Title") = TBTitle.Text m_dtContacts.Rows(m_rowPosition)("Author") = TBAuthor.Textm_dtContacts.Rows(m_rowPosition)("YearPublished") = TBYearPublished.Text m_dtContacts.Rows(m_rowPosition)("Price") = TBPrice.Textm_dtContacts.Rows(m_rowPosition)("LastReadOn") = TBLastReadOn.Textm_dtContacts.Rows(m_rowPosition)("PageCount") = TBPageCount.Text m_dtContacts.Rows(m_rowPosition).AcceptChanges() m_dtContacts.Rows(m_rowPosition).EndEdit() m_dtContacts.AcceptChanges() m_daDataAdapter.Update(m_dtContacts) End Sub After I click save I can navigate through my records and back to the one I just changed and updated and all is well. The changes were made in the table. However, when I close the page and exit out of Visual Web Developer and reopen the database: THE CHANGES WERENT UPDATED!!! This worked all the time in VB2005.net when developing a standard windows app. Can I use the same approach I was using in my code above or am I missing something.
I have read and searched all over and what I'm thinking is that my UpdateCommand, InsertCommand, DeleteCommand, SelectCommand are empty. Do I have to do it this way?
Hi, I have the code below. I need to skip the first row in the datatable as it has the headers. This works now, but my gridview gets the header row inserted as a record.Private Shared Sub InsertData(ByVal sourceTable As System.Data.DataTable, ByVal destConnection As SqlConnection) ' old method: Lots of INSERT statements ' first, create the insert command that we will call over and over: destConnection.Open() Using ins As New SqlCommand("INSERT INTO [tblAppointmentDisposition] ([contactdate], [dnbnumber], [prospectname], [businessofficer], [phonemeeting], [followupcalldate2], [phonemeetingappt], [followupcalldate3], [appointmentdate], [appointmentlocation], [appointmentkept], [applicationgenerated], [applicationgenerated2], [applicationgenerated3], [comments], [newaccount], [futureopportunity]) VALUES (@contactdate, @dnbnumber, @prospectname, @businessofficer, @phonemeeting, @followupcalldate2, @phonemeetingappt, @followupcalldate3, @appointmentdate, @appointmentlocation, @appointmentkept, @applicationgenerated, @applicationgenerated2, @applicationgenerated3, @comments, @newaccount, @futureopportunity)", destConnection) ins.CommandType = CommandType.Text ins.Parameters.Add("@contactdate", SqlDbType.Text) ins.Parameters.Add("@dnbnumber", SqlDbType.Text) ins.Parameters.Add("@prospectname", SqlDbType.Text) ins.Parameters.Add("@businessofficer", SqlDbType.NVarChar) ins.Parameters.Add("@phonemeeting", SqlDbType.Text) ins.Parameters.Add("@followupcalldate2", SqlDbType.Text) ins.Parameters.Add("@phonemeetingappt", SqlDbType.Text) ins.Parameters.Add("@followupcalldate3", SqlDbType.Text) ins.Parameters.Add("@appointmentdate", SqlDbType.Text) ins.Parameters.Add("@appointmentlocation", SqlDbType.Text) ins.Parameters.Add("@appointmentkept", SqlDbType.Text) ins.Parameters.Add("@applicationgenerated", SqlDbType.Text) ins.Parameters.Add("@applicationgenerated2", SqlDbType.Text) ins.Parameters.Add("@applicationgenerated3", SqlDbType.Text) ins.Parameters.Add("@comments", SqlDbType.Text) ins.Parameters.Add("@newaccount", SqlDbType.Text) ins.Parameters.Add("@futureopportunity", SqlDbType.Text) ' and now, do the work: For Each r As DataRow In sourceTable.Rows For i As Integer = 0 To 16 ins.Parameters(i).Value = r(i) Next ins.ExecuteNonQuery() 'If System.Threading.Interlocked.Increment(rowscopied) Mod 10000 = 0 Then 'Console.WriteLine("-- copied {0} rows.", rowscopied) 'End If Next End Using destConnection.Close() End Sub
I'm reading XML data into a DataTable that is populated into a datagrid. From here I need to update database and wanted to know how to Fill a DATA ADAPTER with a DATA TABLE? I'm familiar with updating using a SQL command, but in this case, i have the dataTable already created from XML. Please help. Thanks,
With C#, ADO.net, and SQL Server, is there an easy way to run some sort of query that will return only the structure of a table but not have any data in it? Put another way, I want to create a DataTable that is empty but has exactly the same columns as its associated Table in SQL Server.Robert W.
Hello. I have 2 diffrent tables in the database, is it possible to select both of those back to c# on the same time? I DONT want to combine the tables, just select them into 2 diffrent datatables in one select statement? At the moment, i have something like: function XXOpenDBCon();mCom.Parameters.Clear();mCom.CommandText = "Stuff_GetMovieCategories";myAdap = new SqlDataAdapter();myTable = new DataTable();myAdap.SelectCommand = mCom;myAdap.Fill(myTable);CloseDBCon();return myTable; Can i ask the database to perhaos retrieve Stuff_GetMovieCategories and on the same time retrieve Stuff_MostViewedMovies? So the SP does 2 select statements and returns them, i get in the function above 2 datatables with the information, one datatable with Categories and one table with MostViewedMovies. Is this possible?
Please help guys,I have a DataTable filled from the parsing of a csv file by the OleDb text driver.This DataTable could on occassion contain in excess of 2000 rows.I want to be able to batch the inserts to my backend sql table and be able to recorver on errors during the insert.i.e, maybe send the first 500 rows to insert via an insert dynamic text.... really don't know the optimal insert technic to use.but, if I get an error on say the third batch, I want to be able to recorver, and not have to start all over again and continue the inserts from the batch that failed.....Please help... what is the best way to perform the inserts and how can I track these inserts and recorver on errors like power failures or sql server unavailable etc.Please help....
hello, i'm using asp.net 2 with VB, i have a table in my db named 'exams' and i have 6 columns in this table one for question number and one for the question and 3 columns for 3 answers and a last column for the right answer, now in my page i want to show 7 questions and each question has 3 answers that i can choose between them i want the question appear in datatable and the answers in radiolist i have a little code for that but it shows an error it says "no row at position 1" so hope u guys can help : Dim con As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|aspnetdb.mdf;Integrated Security=True;User Instance=True") Dim a As New ArrayList(8) Dim i As New Integer i = 0 Dim d As New DataSet() Dim cmd As New SqlDataAdapter("select top(7) question from exams", con) cmd.Fill(d, "exams") a.Add(d.Tables.Item(0, 1)) i = i + 1 Dim ta As New DataTable ta.Rows(i).Item(0).text = d.Tables(0).Rows(0)(i)and by the way this code is for the questions i still dont have the code for the answers that will appear in a radiolist hope u can help .thanks