Gridview Binding With SqlConnection Objects...

Jun 19, 2007

Hello All, I am new to data access and

i have got the problem to display the data into the page by binding the gridview with sqlConnection, sqlCommand and sqlDataReader objects.  The actually code is written as:protected void Page_Load(object sender, EventArgs e)

{
if (!Page.IsPostBack)

{SqlConnection myConnection;

SqlCommand myCommand;SqlDataReader myReader;

myConnection = new SqlConnection();myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["LatteConnectionString"].ConnectionString;

myCommand = new SqlCommand();myCommand.CommandText = "select * from AntiVirusVendors";myCommand.CommandType = CommandType.Text;

myCommand.Connection = myConnection;

myCommand.Connection.Open();myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = myReader;

GridView1.DataBind();

myCommand.Dispose();

myConnection.Dispose();

}

 

}

 

and the GridView in html is listed as:

<div>

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

</div>

So the problem is ---> there is nothing shown in the page, no errors no anything.... just the empty page.

Any ideas would be appreciated. Thanks in advance!

Joe

View 1 Replies


ADVERTISEMENT

Help!!! Gridview Binding

Mar 20, 2008

Hey guys, Am in need of help please, basically the program im working with at the moment is when you add a New Contract, it will grab the Contract Number you have entered, Post it over to another page, then using that number bind a Gridview. The SQL being "SELECT Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent FROM ECS_Contracts_Test WHERE Contract_Number = " & conNoVar (this being the Contract Number of the recently added Contract), however then it comes to Bind the Grid it kicks up an System.Data.SqlClient.SqlException: Syntax error converting the nvarchar value
'2009P7899' to a column of data type int.But the Column Contract_Number is set to Varchar and all I really want to do is to create this gridview using this criteria and not convert anything! The Contract_ID is an int, which is needed as I increment it. Heres the error code:   Public Sub BindtheGrid()'Bind the Contract Grid, where ContractID is used
Dim SQL As String = "Contract_ID, Contract_Number, Start_Date, End_Date, Quarterly_Rent"
Dim objConn As SqlConnection = New SqlConnection(ConnectionString)
Dim cmdstock As SqlCommand = New SqlCommand("SELECT " & SQL & " FROM ECS_Contracts_Test WHERE Contract_Number = " & contractQueryID, objConn)
cmdstock.CommandType = CommandType.Text
objConn.Open()
GridView1.DataSource = cmdstock.ExecuteReader()
GridView1.DataBind()
objConn.Close()
End Sub If you need any more information then please let me know. Mucho Aprreciated   

View 1 Replies View Related

Binding Gridview From Two Different Tables

Jul 30, 2007

Hi all,
The Scenario:
Database1:Table1(callingPartyNumber,originalCalledPartyNumber, finalCalledPartyNumber, DateTimeConnect, DateTimeDisconnect, Duration)
Database2:Table2(Name,Number)
Output in Gridview:




callingPartyNumber
Name
originalCalledPartyNumber
finalcalledPartyNumber
dateTimeConnected
dateTimeDisconnected
Duration (HH:MM:SS)
I bind gridview programatically using DataTable and stored procedures. The data comes from a table (Table1) in a database (Database1) on SQL Server. The gridview displays fields callingPartyNumber, originalCalledPartyNumber, finalCalledPartyNumber, DateTimeConnect, DateTimeDisconnect and Duration in this order. All the columns in this gridview are databound columns.
I have another table (Table2) in a seperate SQL Server database (Database2) but on the same server which maps the callingPartNumber value with the name attached with that number. Note that the field names in Table2 are different from the field names in Table1. Is it possible to display the Name field also in the gridview after the first field callingPartyNumber and then the other fields.
Its like data coming from two tables into the gridview.
Thanks

View 7 Replies View Related

Can Anyone Spot My Error Please Binding A Gridview

Jan 21, 2008

Hi All
I am trying to bind a gridview to my sql express database through code but my data is not being displayed, i dont get any errors though?
If i bind it using an sql datasource it works fine so i know my connection string works and there is data in my database
my code is as follows
thanks
gibbo
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ReadRecords(GridView1, "Select * from Actions")
End Sub

Public Shared Function GetConnString() As String
Return System.Configuration.ConfigurationManager.ConnectionStrings("actionsConnectionString2").ConnectionString
End Function

Private Sub ReadRecords(ByVal datagrid As GridView, ByVal SQL As String)
Dim ConnString As String = GetConnString()
Dim SqlString As String = SQL
Using conn As New SqlClient.SqlConnection(ConnString)
Using cmd As New SqlClient.SqlCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader()
datagrid.DataSource = reader
datagrid.DataBind()
End Using
End Using
End Using
End Sub


Connection String

<add name="actionsConnectionString2" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=&quot;|DataDirectory|actions.mdf&quot;;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
 

View 8 Replies View Related

Binding A SqlDataSource, To A GridView At Runtime

Mar 8, 2006

Hello
I'm experiencing some problems, binding a SqlDataSource to a GridView.
The following code creates the SqlDataSource:            string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;            string strProvider = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;                        SqlDataSource ds = new SqlDataSource(strProvider, strConn);            ds.SelectCommand = "SELECT * FROM rammekategori";
Then i bind the SqlDataSource to a GridView:
         GridView1.DataSource = ds;            GridView1.DataBind();
 
ErrorMessage:
Format of the initialization string does not conform to specification starting at index 0.
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.Line 24:             GridView1.DataBind();Am i totally off target here? Can it be something about, that you have to set the datasource of the gridview, before the Page_Load event?
 
Thanks - MartinHN

View 9 Replies View Related

Binding A Gridview To Sqldatasource On Button Click

Mar 3, 2008

 i am using 2 textbox to search name and instituition of some students. on button click  need to display the result on gridview. but i dont get any result.. pl adviceSqlDataSource1.SelectCommand = "SELECT Sname, Address, Instituition, Role, Testgroup, Email FROM std_det WHERE (Sname LIKE '%'+@Param1+'%') AND (Instituition = 'RASET') AND (Role LIKE '%'+@Param2+'%') AND (Instituition = 'RASET')";            name.ControlID = "TextBox3";            name.DefaultValue = "%";            name.Name = "Param1";            name.PropertyName = "Text";            inst.ControlID = "TextBox4";            inst.DefaultValue = "%";            inst.Name = "Param2";            inst.PropertyName = "Text";            //SqlDataSource1.Select(DataSourceSelectArguments.Empty);            SqlDataSource1.SelectParameters.Add(name);            SqlDataSource1.SelectParameters.Add(inst);            SqlDataSource1.DataBind();            //DataView dv = (DataView)this.SqlDataSource1.Select(DataSourceSelectArguments.Empty);            GridView2.DataSourceID = "SqlDataSource1";                        GridView2.DataBind();

View 2 Replies View Related

Performance Problems When Using Multiple SqlConnection Objects?

Feb 9, 2007

Hello,
 
I am planning to use three databases on the local SQL Server. DB1 will be for App1, DB2 for App2, and DB3 will hold tables, that both, App1 and App2 need to access.
 
Obviously, I need in App1 and App2 at least two SqlConnection and SqlCommand objects, one that access their respective databases, and one that will access DB3.
 Will this result in a worse performance? (The using of two SqlConnection objects in one aspx page as example, and switching them)
Should I for better performance get rid of DB3 and add the tables there to DB1 and DB2 ? (Thus multiplying data, but, if the performance will be much better, it will be fine with me)
 
I would be thankful for any advices.

View 4 Replies View Related

The Insides Of The SqlConnection, SqlCommand, And SqlDataReader, Objects

Mar 22, 2008

Im just curious, can anyone explain what exactly the methods do within the objects (sqlconnection, sqlCommand, SqlDataReader) . and why it takes three objects to carry out a connection. Php only used one object I believe.
 
But most of all i would like to know how they work. like sqlCommand carrys the connection (sqlcommand.connection) while sql connection retrieves the address connection (sqlconnection(connectionstring)). what does Sqlconnection do once it gets this address. and what does it give sqlcommand when its ready to take out the query and put it in the reader once the sqlconnection.open()  to make it simple. let me put it this way
 sqlConnection con = new SqlConnection(_connectionstring);    // server address comes through here. along with security and database name what exactly does the object con do ? it runs through the constructor and does what ?
SqlCommand cmd = new SqlCommand();  cmd.Connection = con;  //So now what ever the SqlConnection did with the _connectionstring. it now passes it through the connection property. the connection property does something with value of con. what is it ??
cmd.CommandText = 'select, ID, Name, Price.....'       // I think i know what that does
con.Open()                    // I know that the connection opens here. but what exactly does this method do to make it open ????????
sqlDataReader reader  = cmd.ExecuteReader();    im some what confused with this one. sqldataReader reader was never declared and its not even a static method. What exactly is it ?????       cmd.ExecuteReader() now takes the property connection which did something with the con value. then it used the commandtext property to request the query. it takes con.open does something and now its execute reader. Im a lil confused
last but not least, con.close() what does that do ?? its alot but can anyone fill me in. or should i say fill(me); in lol, get it. never mind.
                                                                                              

View 1 Replies View Related

How To Open Multiple SqlConnection Objects In A SqlServer Project

Jun 5, 2006

I have a sql server project where I have added 1 stored procedure (named StoredProcedure1) and 1 class (named MyClass). MyClass has two functions Func1() and Func2(). The stored procedure simply instantiates MyClass and calls Func1().

Func1() creates a SqlConnection object using "context connection=true" - opens the connection and then calls Func2(). Func2() also creates a SqlConnection object using "context connection=true" - and attempts to open the connection. However when attempting to the Open() call inside Func2(), the code just exits. What gives? The code is pasted below, thanks!

*******THE STORED PROCEDURE**************
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using SqlServerProject1;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void StoredProcedure1()
{
// Put your code here
MyClass obj = new MyClass();
obj.Func1();
obj = null;
}
};

*******THE CLASS "MYCLASS"**************
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public class MyClass
{
public MyClass()
{

}

public void Func1()
{
using ( SqlConnection conn = new SqlConnection("context connection=true") )
{
conn.Open();

Func2();
conn.Close();
}
}

public void Func2()
{
using ( SqlConnection conn = new SqlConnection("context connection=true") )
{
if ( conn.State != ConnectionState.Open )
conn.Open();

if ( conn.State == ConnectionState.Open )
conn.Close();
}
}
}

View 1 Replies View Related

Want Error Message To Appear When No Database Results Were Returned In GridView, Also Other GridView Issues.

Jun 12, 2008

Hi, I am seeking a hopefully easy solution to spit back an error message when a user receives no results from a SQL server db with no results. My code looks like this What is in bold is the relevant subroutine for this problem I'm having.   Partial Class collegedb_Default Inherits System.Web.UI.Page Protected Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] WHERE [name] like '%" & textbox1.Text & "%'" SqlDataSource1.DataBind() If (SqlDataSource1 = System.DBNull) Then no_match.Text = "Your search returned no results, try looking manually." End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End Sub Protected Sub reset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles reset.Click SqlDataSource1.SelectCommand = "SELECT * FROM [college_db] ORDER BY [name]" SqlDataSource1.DataBind() End SubEnd Class  I'm probably doing this completely wrong, I'm a .net newb. Any help would be appreciated. Basically I have GridView spitting out info from a db upon Page Load, but i also have a search bar above that. The search function works, but when it returns nothing, I want an error message to be displayed. I have a label setup called "no_match" but I'm getting compiler errors. Also, next to the submit button, I also have another button (Protected sub reset) that I was hoping to be able to return all results back on the page, similar to if a user is just loading the page fresh. I'd think that my logic would be OK, by just repeating the source code from page_load, but that doens't work.The button just does nothing. One final question, unrelated. After I set this default.aspx page up, sorting by number on the bottom of gridview, ie. 1,2,3,4, etc, worked fine. But now that paging feature, as long with the sorting headers, don't work! I do notice on the status bar in the browser, that I receive an error that says, "error on page...and it referers to javascript:_doPostBack('GridView1, etc etc)...I have no clue why this happened. Any help would be appreciated, thanks! 

View 2 Replies View Related

Putting Names Of Objects To Control-flow Loop Creating Objects

Dec 27, 2006

please help newbieI need to create a lot of objects the same type (let's say: schemas)I wish to use paramerized block in loop to do so.- how to put names of my objects to such control-flow?belss you for help

View 5 Replies View Related

SQL Server 2012 :: Select Data From XML - Objects Within Objects?

Nov 20, 2013

passing serialised objects to a stored procedure for the purpose of data inserts. I see this as being a way to handle multiple row inserts efficiently.

However, in my limited use of XML data I am not so sure how to link the data when I have a dependency on another "object" within the serialised XML.

Below is a code snippet showing what I have so far.

The first insert statement works fine - but how to retrieve the identifier created by the DB - I want to use an SQL statement that finds the record in the table based on the XML representation (of the PluginInfo), allowing me to insert the ConfigurationInfo with the correct reference to the PluginInfo

DECLARE @Config NVARCHAR(MAX)
DECLARE @Handle AS INT
DECLARE @TransactionCount AS INT
SELECT @Config = '
<ConfigurationDirectory >
<ConfigurationInfo groupKey="Notifications" sectionKey="App.Customization.PluginInfo"

[code]....

View 1 Replies View Related

Help With Binding

Jun 16, 2007

hi guys! help please..how will bind my texbox (TxtLastName) to my dataset (dsLastName) column (User_LastName). Thanks in avdance!

View 1 Replies View Related

Binding SQL To An IP

Dec 6, 2006

I've got SQL 2k5 on a Win2k3 box. I'm trying to find information or a how to on how to set up SQL to only respond to requests on a particular IP

Can anybody point me in the right direction or explain how?



v

View 1 Replies View Related

Binding Error

Oct 1, 2007

Hi all
 I have a form view which uses a SQL data source control to retrieve it's data from the sql express database
the form view is used for view,edit,delete and insert data into the database
in the insert mode I have two dropdownlists, where the second one is depending on the first one to retrieve the correct data from the data base BUT
when selecting a value in the first dropdownlist it give me the following erro:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
 
Please How can do this
any help is appriciated
bye

View 1 Replies View Related

Data Binding, Sql Etc!

Jun 3, 2008

 Hi guys, I am about to bind my websites user inputted values into my database. I intend to use sql for this. THe site is very basic, dropdownlists and textboxes. The user is required to choose values and write in questions. Now these inputs ought to be stored somewhere right??, so for that i am using sql. Now i know sql, but how do I store data from a website and all, I have no clue, someone give me basic steps on how to go about doing this pleaseeeeee!!!

View 2 Replies View Related

Inner Select Binding?

Mar 24, 2006

I have this stored procedure that almost works:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
 
 
ALTER PROCEDURE [dbo].[udForumTopicMessageByForumTopicID]
@ForumTopicID int
AS
SELECT
ftm_parent.ForumTopicMessageID AS "ForumTopicMessageID",
ftm_parent.ForumTopicID AS "ForumTopicID",
ftm_parent.ContactID AS "ContactID",
ftm_parent.MessageTitle AS "MessageTitle",
ftm_parent.MessageText AS "MessageText",
ftm_parent.ApprovedInd AS "Approved",
ftm_parent.ReviewedInd AS "ReviewedInd",
ftm_parent.ParentMessageID AS "ParentMessageID",
ftm_parent.OwnerCompany AS "ForumTopicMessageOwnerCompany",
ftm_parent.CreateUser AS "ForumTopicMessageCreateUser",
ftm_parent.UpdateUser AS "ForumTopicMessageUpdateUser",
ftm_parent.CreateDate AS "ForumTopicMessageCreateDate",
ftm_parent.UpdateDate AS "ForumTopicMessageUpdateDate",
'('+CAST(ChildResponseCount As VARCHAR(10))+')' As "ChildResponseCount",
(T_Contact.Lastname + ', ' + T_Contact.Firstname) As "ContactName"
FROM [T_ForumTopicMessage] as ftm_parent
INNER JOIN [T_Contact] ON [T_Contact].ContactID = ftm_parent.ContactID
Left JOIN
(Select
COUNT([T_ForumTopicMessage].ForumTopicMessageID) As "ChildResponseCount",
MAX([T_ForumTopicMessage].ParentMessageID) AS "ParentMessageID"
FROM
[T_ForumTopicMessage]
WHERE [T_ForumTopicMessage].ParentMessageID = ftm_parent.ForumTopicMessageID
group by [T_ForumTopicMessage].ForumTopicMessageID)
as ftm_child ON ftm_parent.ForumTopicMessageID = ftm_child.ParentMessageID
WHERE ftm_parent.ForumTopicID = @ForumTopicID
ORDER BY ftm_parent.CreateDate
See the purple ftm_parent.ForumtopicMessageID.  If I hard-code that to a 2, this works.  With the fieldname there, SQL Server Management Studio says:
Msg 4104, Level 16, State 1, Procedure udForumTopicMessageByForumTopicID, Line 9
The multi-part identifier "ftm_parent.ForumTopicMessageID" could not be bound.
If any experts out there can help me out with this, I'm sure it wouldn't take much to fix.
 

View 4 Replies View Related

Trouble Binding

Feb 20, 2007

I am building a web app with a sql db.

The data base is all fine.

I can display information from the db with a gridview from a sqldata source....all ok

What I cant seem to do, is tie a drop down list box with a,b,,c items to call the column

with the ..."all items starting with the letter a"

I have writen SELECT WHERE statement that (a%) which works fine at pulling what I want to the gridview

and displays it fine.

Does the gridview conect to the source..... and the drop dlbox connect to the grid

Or each have its own conection to the source........or drop conects to source and grid

conects to

You can see my dilema .

c# web dev



View 1 Replies View Related

Binding COUNT

Feb 22, 2007

hi guys,

i want to count the number of times a particular data occurs in a table and display that data in a listbox

initially i planned to count the number of occurrences and bind that number to a variable for further manipulation but i have no idea how to do the binding part

how do i solve this?

thanx

View 3 Replies View Related

SqlCONNECTION

Jul 27, 2006

Public Conn As New SqlConnection("Data Source=localhost;Initial Catalog=tblUsers;UID=XXXX;pwd=XXXX")Public Conn As New SqlConnection("Data Source=XX.XXX.XX.XXX;Initial Catalog=tblUsers;UID=XXXX;pwd=XXXX")
This two commands are in my application.  I switch between the two so I can test my application.
When I put my application on the server, I use the localhost SQLCONNECTION.  The other is commented out.  However, the application continues to connect to the server with the address that is commented out.
THIS IS VERY FRUSTRATING...  HELP!!!!

View 1 Replies View Related

SqlConnection ???????

Oct 2, 2006

Hi, Someone can explain to me what happend in this situation...i have this and want to call a procedure with connection parameters protected void Button1_Click(object sender, EventArgs e)
{

SqlConnection edo = new SqlConnection();
edo.ConnectionString = "server=myserver; uid=admin; pwd=; " +
"database=name1";
SqlCommand com = edo.CreateCommand();
com.CommandType = CommandType.Text;
My_proc(edo, com);
}
protected void My_proc(SqlConnection edo , SqlCommand com)
{
try
{edo.Open();
}
catch{}
finally{ edo.close();}
}

Well what happend with the SqlCommand and SqlConnection when return to Button_Click() Are they alive? Can be used in Buton_Click like parameters for another procedure? or i have to create it again?Thx in advance..                 

View 1 Replies View Related

Sqlconnection

Oct 16, 2006

please help me !!!?I have a problem with sqlconnection definition when I add the sqlconnection from toolbox :like this: Imports System.Data.SqlClientPartial Class _Default    Inherits System.Web.UI.Page    Private Sub InitializeComponent()        Me.sqlConnection1 = New System.Data.SqlClient.SqlConnection        Me.sqlConnection1.ConnectionString = "Data Source=server;Initial Catalog=masterstd;User ID=sa"        Me.sqlConnection1.FireInfoMessageEventOnUserErrors = False    End Sub    Private WithEvents sqlConnection1 As System.Data.SqlClient.SqlConnection    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load        If Not IsPostBack Then            Dim cmduniversity As SqlCommand            Dim dtruniversity As SqlDataReader            cmduniversity = New SqlCommand("select * from university", sqlConnection1)            sqlConnection1.Open()            dtruniversity = cmduniversity.ExecuteReader            dtruniversity.Close()            sqlConnection1.Close()        End If    End SubEnd Classin the sqlconnection.open the nullrefrence exception occures butwhen i define myself this exception dosn't occure.like this:   Imports System.Data.SqlClientPartial Class _Default    Inherits System.Web.UI.Page    Private Sub InitializeComponent()       End Sub    Private WithEvents sqlConnection1 As System.Data.SqlClient.SqlConnection    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load        If Not IsPostBack Then            sqlConnection1 = New SqlConnection            sqlConnection1.ConnectionString = "Data Source=server;Initial Catalog=masterstd;User ID=sa"            sqlConnection1.FireInfoMessageEventOnUserErrors = False            Dim cmduniversity As SqlCommand            Dim dtruniversity As SqlDataReader            cmduniversity = New SqlCommand("select * from university", sqlConnection1)            sqlConnection1.Open()            dtruniversity = cmduniversity.ExecuteReader            dtruniversity.Close()            sqlConnection1.Close()        End If    End Subwhere is the problem?

View 2 Replies View Related

SqlConnection

Apr 28, 2007

 Can someone help me out? I am trying to establish a SQL server connection in my C# code. My C# code crasheds though. Can someone tell me what Iam doing wrong? Here is the C# code:
 
    SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["TheDividerConnectionString"]);
 Here is the connection string as defined in the web.config file:
 <connectionStrings>  <add name="TheDividerConnectionString" connectionString="Data Source=BVCOMPUTERSQLEXPRESS;Initial Catalog=TheDivider;Integrated Security=True"   providerName="System.Data.SqlClient" /> </connectionStrings>
 

View 21 Replies View Related

Sqlconnection

Jun 11, 2007

is their any code which can check my project for any connections which  are open and never closed.
frm 1.1,sql server 2000

View 1 Replies View Related

Sqlconnection

Jan 24, 2008

Would anyone ahve any ideas why when i debug this code, it stops and freezes at cn.open(); A raw sql query against the DB works in this format.
int top=10;SqlConnection cn = new SqlConnection("Data Source=blah;Initial Catalog=blah;Integrated Security=blah");
SqlCommand cmd = new SqlCommand("SELECT DISTINCT TOP (@nrows) [CustNu] FROM [Customer] WHERE [CustNu] like @term", cn);cmd.Parameters.AddWithValue("nrows", top);cmd.Parameters.AddWithValue("term", prefixText + "%");
 
List <string> suggestions = new List<string>();
cn.Open();

View 5 Replies View Related

Pb With SQLConnection

Mar 13, 2008

 HiI would like to have some help for my problem.I'm trying to retreive the connectionString "MyConnectionString" from app.config using method 1 or 2 to get a connection to my DB (without any success.) --> Partial codepublic SqlConnection GetConnection()        {            // reference to System.Configuration Library is done                   1    SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);--> thrown NullReferenceException on   Conn.Open();                   2    SqlConnection Connection = new SqlConnection(ConfigurationSettings.AppSettings["MyConnectionString"]);--> thrown InvalidOperationException ConnectionString not initialised            return Connection;        }       public Contest GetContestFromDB()        {            SqlConnection Conn = GetConnection();            Conn.Open(); ->> thrown Exception 1 or 2...Here my app.config :<?xml version="1.0" encoding="utf-8"?><configuration>  <appSettings>    <clear/>    <add key="MyConnectionString" value="Server=.SQLExpress;AttachDbFilename=D:Documents and Settings0xMesdocumentsApp_DataShopperDB.MDF;Database=ShopperDB.MDF;Trusted_Connection=Yes;"></add>  </appSettings>  <connectionStrings>    <clear/>   --> using <clear/> to avoid to load from machine.config    <add name="MyConnectionString" connectionString="Server=.SQLExpress;AttachDbFilename=D:Documents and Settings0xMes documentsApp_DataShopperDB.MDF;Database=ShopperDB.MDF;Trusted_Connection=Yes;"></add>  </connectionStrings></configuration> I'm using Visual Studio 2008 with SQLServer 2005 Express Embedded and WindowsXP SP2 .Have you got any idea ?I'm not able to sleep anymore...And I've test this code in ASP.net with the same ConnectionString in the web.config file and it works !!I'm lost.By the way, thx if ou get an answer  ww4ss

View 2 Replies View Related

SQLConnection

Aug 24, 2004

Hi
I have the next simple code, what do i have to change to match it to SQL?
The code:
Sub Page_Load (Source As Object, E as EventArgs)
dim strConn as string =("Provider=" & "Microsoft.Jet.OLEDB.4.0;" & _
"Data Source =C:webspacesegolforferaforfera.co.ildbguestbook.mdb")

Dim MySQL as string = "SELECT Name, EMail, URL, Comment FROM Guestbook"
Dim MyConn as New OleDBConnection (strConn)
Dim Cmd as New OleDBCommand (MySQL, MyConn)
MyConn.Open ()
rptGuestbook.DataSource = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
rptGuestbook.DataBind()
End Sub
Thank's and have a good day.

View 3 Replies View Related

Help With Connecting To SQL Database And Binding

Jun 30, 2006

I am new to .net and I am using Visual Web Developer 2005 Express with SQL Server 2005 Express.  What I would like to do is connect to my SQL database (which resides in the app_data folder) and open a table and pull out a field and place it in either a textbox or label on the page. No editing or deleting. Just simple one field binding.  By the way, I can do this with all the cool built-in tools of VWD, but I want to know how to do it all by hand.  I would really appreciate it if someone could help me out.

View 3 Replies View Related

Binding A Text Box To A Datasoure - Please Help

Aug 14, 2006

I have search for answers to the all over google and every thing I have found so far did not work for some reason or anothr. .
Here is what I am looking for I am codeing in Visual Studio using C#. I have been able to crate a connection and create taxt boxes with a submit button that when it is presed enters data in to a database (Sql server) what I have been unable to do is:
1. Display data in a text box.
2. Update data
3. create buttons to navagate through fields.
I know I can do this with the gridview or datagrid but in really need a custome form for what I am doing.

View 1 Replies View Related

How To Get The Value Of A SQL Query Before Binding It To DataGrid?

Dec 4, 2006

I am using C#.Net, Visual web Developer, SQL server 2000. I have a SQL query which I am binding it to a DataGrid. SQL : "SELECT ord_number, ord_ID, ord_split, ord_Name, ETD_Date, OSP_FSD FROM ORDERS" In My DataGrid I have a dynamic databound column. I am able to bind one column to this databound column using following code. BoundColumn ETDDate = new BoundColumn(); ETDDate.HeaderText = "ETD Date"; ETDDate.DataField = "OSP_FSD"; mygrid2.Columns.AddAt(ETDDate); but now I want to bind this databound column based on the following criteria to two different database columns. if(ord_split = 1) { ETDDate.DataField = "OSP_FSD"; } else { ETDDate.DataField = "ETD_Date"; } How to get value of ord_split before binding SQL to teh DataGrid? i.e I just want to take value of ord_split and not all the values of SQL. Please Help!

View 1 Replies View Related

Binding A Texbox To A SQLDataSource

Feb 13, 2007

This is an easy question.  I thought I have databinded a textbox to a SQLDataSource.  But now I do not see how to do that now.  Can somebody help with this?
Thanks,

View 1 Replies View Related

Binding Textbox With SqlDataSource

Mar 9, 2007

Hi,    I wants to bind textbox with sqldatasource in c#.net so I am using following code and has following error... Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.Source Error:



Line 22: Line 23: System.Data.DataView dv = (DataView) SqlDataSource1.Select(System.Web.UI.DataSourceSelectArguments.Empty);Line 24: TextBox1.Text = dv[0]["Proid"].ToString();Line 25: Line 26: }Please, anybody knows solution tell me 

View 1 Replies View Related

Default Value Or Binding = (getdate())

Apr 1, 2007

Ok I have a script to generate a database, and newly added to the database is a date fild for a specfic table. I have the 'Default value or binding' set to (getdate()) how exactly would you add that to the script for then the table is initialy generated. Or is it soemthing I would need another script to do right after the table generation.This is the script for the table in question:CREATE TABLE [dbo].[cust_file] ( [id] [int] IDENTITY (1, 1) NOT NULL , [customer_id] [int] NULL , [filename] [varchar] (255) NULL , [filedata] [image] NULL , [contenttype] [varchar] (255) NULL , [length] [int] NULL,  [added_date] [datetime] NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GO
Any help would be great,Tim MeersWannabe developer.

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved