ASP.NET DataGrid Problem

Feb 4, 2006

Hi,

As a relative newbie to SQL Server/ASP.NET I'm hoping someone here
can help with my problem. I'm developing a timesheet application in
ASP.NET C# using Visual Studio 2003 with a database built in MSDE.
One of my forms needs to return a simple list of resources from my
database. I have followed the guide on the MSDN libraries, but for
some reason I continuously get the same error message.

What I've done so far is Create the database, tables, and populate
with some sample data using using Server Explorer in Visual Studio. I have
connected to the database (using integrated security) and I am
trying to get the contents of the Resource table to appear on my
form. I have then created a DataAdapter (tested the connection, set
the SQL as a simple SELECT * from Resource, etc), which also generates an sqlConnection for me. To test this I have previewed the generated data, and it returns what I want, so I
have chosen to generate a DataSet of this. I am then trying to get
this data into a simple DataGrid. On the properties of the DataGrid
I have changed the DataSource to point at my Dataset. As I
understand it, I then have to add the following to my Page Load
section of my code.

sqlConnection1.Open();
this.sqlDataAdapter1.Fill(this.dsResource);
DataGrid1.DataBind();
sqlConnection1.Close();

The form builds fine, but when I browse to the particular form I get
the following error for the sqlConnection1.Open(); line. If I remove this line the error simply moves to the line below.

Exception Details: System.Data.SqlClient.SqlException: Cannot open
database requested in login 'SCMS'. Login fails. Login failed for
user 'AL-NOTEPADASPNET'.

To me this is an error with my connection string. My database
instance is actually 'AL-NOTEPADVSDOTNET'.  However the properties
for sqlConnection1 are pointing to the correct datasource. I do not
know why the application is looking for user 'AL-NOTEPADASPNET'. It does not exist, to my knowledge. Do I need to grant access to this user? If so, how would I do it? Bearing in mind I am using MSDE, and do not have Enterprise Manager.

Any help with this would be greatly appreciated, as I get the same
error with my code for forms-based login...


Thanks in advance..

View 2 Replies


ADVERTISEMENT

SQL And DataGrid

Aug 10, 2007

I need to take 8 indiviual parts of a table and combine then into 1 Column of a Datagrid.  Is this even possible, if so how?
 example:
The DB contains:
Comp1 Comp2 Comp3 ... Comp8
 
The DG should say
header --> Comp
Data --> Comp1, Comp2, Comp3, ..., Comp8
 

View 4 Replies View Related

Datagrid

May 6, 2004

hey all

i have 2 tables
1. Location (locid, name)
2. Product (pid, locid, productname, ...etc)

right now i do a select * from product where locid ='locid', and a datagrid with colums
ProductId | ProductName | AvailableIn

how do i do a select * from Location where locid ='locid' and show Location Name in the datagrid?

ProductId | ProductName | AvailableIn
123456 | testing | Somewhere (instead of the locid)

thanks

View 2 Replies View Related

Can Not Update In DataGrid - C#

Aug 29, 2006

Here is my code : string    connstring = System.Configuration.ConfigurationSettings.AppSettings["myconn"];        string selectquery =  "Select * from nhacungcap";        protected System.Web.UI.WebControls.DataGrid DataGrid1;        string insertquery = "Insert into nhacungcap(mancc,tenncc,diachi,dienthoai) values(@mancc1,@tenncc1,@diachi1,@dienthoai1)";string updatequery = "Update nhacungcap set mancc=@mancc, tenncc=@tenncc, diachi=@diachi, dienthoai=@dienthoai where (mancc=@mancc)";            myconnection.Open();            SqlCommand updatecommand = new SqlCommand(updatequery,myconnection);// sua truong mancc            updatecommand.Parameters.Add(new SqlParameter("@mancc",SqlDbType.VarChar,10));            updatecommand.Parameters["@mancc"].Value = DataGrid1.DataKeys[e.Item.ItemIndex];// sua truong tenncc            updatecommand.Parameters.Add(new SqlParameter("@tenncc",SqlDbType.NVarChar,50));            updatecommand.Parameters["@tenncc"].Value = ((TextBox) e.Item.Cells[3].Controls[0]).Text;// sua truong diachi            updatecommand.Parameters.Add(new SqlParameter("@diachi",SqlDbType.NVarChar,200));            updatecommand.Parameters["@diachi"].Value = ((TextBox) e.Item.Cells[4].Controls[0]).Text;// sua truong dienthoai            updatecommand.Parameters.Add(new SqlParameter("@dienthoai",SqlDbType.Char,10));            updatecommand.Parameters["@dienthoai"].Value = ((TextBox) e.Item.Cells[5].Controls[0]).Text;// kiem tra lenh thuc thi            int result1 = updatecommand.ExecuteNonQuery();                         myconnection.Close();// dieu kien kiem tra            if (result1 > 0 )             {                lbcheck.Text = "Cập Nhật Thành công  !";            }// hien thi du lieu                        hienthidulieu();  And my error appear, when I edit value in datagrid, I only update all value fields, without value @mancc . Hu hu hu, I don't know what i must do with it.

View 1 Replies View Related

Datagrid Delete

Jul 24, 2007

Hi I'm having a problem deleting rows from my datagrid. Basically I hit delete and a message box pops up and asks if Im sure I want to delete so I hit yes and then I get the following error --> Could not find stored procedure 'delete from SECTION_TBL where SECT_ID = @SECT_ID'.
 Is it my code thats wrong or is our test sql server that is the problem?1 <%@ Page Language="VB" EnableEventValidation="True" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>
2 <%@ import namespace="System" %>
3 <%@ import namespace="System.Data" %>
4 <%@ import namespace="System.Data.SqlClient" %>
5
6 <script language="VB" runat="server">
7
8 Dim section As String
9 Dim myconnection As SqlConnection
10 Dim myda As SqlDataAdapter
11 Dim ds As DataSet
12
13 Sub Page_Load(ByVal Source As Object, ByVal E As EventArgs)
14 BindData()
15 End Sub
16
17 Sub BindData()
18
19 Dim strConn As String = "server=fileserver; uid=xxx; pwd=xxx; database=NEW_CMS"
20 Dim sql As String = "Select * from SECTION_TBL"
21 myconnection = New SqlConnection(strConn)
22 myda = New SqlDataAdapter(sql, myconnection)
23 ds = New DataSet
24 myda.Fill(ds, "SECTION_TBL")
25 sectList.DataSource = ds
26 sectList.DataBind()
27
28 End Sub
29
30 Private Sub sectList_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles sectList.ItemDataBound
31
32 Dim l As LinkButton
33
34 If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
35 l = CType(e.Item.Cells(0).FindControl("cmdDel"), LinkButton)
36 l.Attributes.Add("onclick", "return getconfirm();")
37 End If
38
39 End Sub
40
41 Sub sectList_DeleteCommand(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
42
43 Dim ConnectionStr As String = ConfigurationManager.AppSettings("ConnStr")
44 Dim conn As SqlConnection
45 Dim cmd As SqlCommand
46 Dim Id As Integer
47
48 Id = CInt(e.Item.Cells(0).Text)
49 conn = New SqlConnection("server=fileserver; uid=xxx; pwd=xxx; database=NEW_CMS")
50 cmd = New SqlCommand("delete from SECTION_TBL where SECT_ID = @SECT_ID", conn)
51 cmd.CommandType = CommandType.StoredProcedure
52 cmd.Parameters.Add("@SECT_ID", SqlDbType.Int).Value = Id
53
54 cmd.Connection.Open()
55 cmd.ExecuteNonQuery()
56 cmd.Connection.Close()
57
58 DataBind()
59
60 End Sub
61
62
63
64 </script>
65
66 <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
67
68 <script language="javascript">
69
70 function getconfirm()
71 {
72 if (confirm("Do you want to delete record?")==true)
73 return true;
74 else
75 return false;
76 }
77
78 </script>
79
80 <table cellpadding="2" cellspacing="2" width="760">
81 <tr>
82 <td>Sections</td>
83 </tr>
84 <tr>
85 <td>
86
87 <asp:DataGrid OnDeleteCommand="sectList_DeleteCommand" ID="sectList" runat="server" DataKeyField="SECT_ID" AutoGenerateColumns="False">
88
89 <Columns>
90
91 <asp:BoundColumn DataField="SECT_ID" Visible="False" />
92
93 <asp:HyperLinkColumn HeaderText="SECTION NAME" DataTextField="SECT_NAME" DataNavigateUrlField="SECT_ID" DataNavigateUrlFormatString="manageSection.aspx?SECT_ID={0}" />
94
95 <asp:TemplateColumn>
96 <ItemTemplate>
97 <asp:LinkButton id="cmdDel" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false" />
98 </ItemTemplate>
99 </asp:TemplateColumn>
100
101 </Columns>
102
103 </asp:DataGrid>
104
105 </td>
106 </tr>
107 <tr>
108 <td></td>
109 </tr>
110 </table>
111
112 </asp:Content> Thanks in advance.
 

View 2 Replies View Related

SQLDataSource WITHOUT Using A Datagrid

Mar 10, 2008

Hi,
 I'm trying to use VS2005 to create an ASP.NET 2.0 application.  As part of this application I need to be able to read value from a SQL2005 database.  I used the connection string builder to create the connection string, but am unable to run a simple SELECT statement.  In .NET 1.1, I was able to do this pretty easily, but am unable to even find the same namespaces in .NET 2.0.
 For example (VS2003):
           'Construct new SQL statement            sqlDBDAHulls.SelectCommand.CommandText = "SELECT COUNT('HullID') FROM Hulls"            iNoRows = sqlDBDAHulls.SelectCommand.ExecuteScalar
            ReDim arrHullClass(iNoRows - 1)            ReDim arrHullDesign(iNoRows - 1)
            ddlHull.Items.Clear()
            For iArrLoop = LBound(arrHullClass) To UBound(arrHullClass)                'Redefine SQL statement                sqlDBDAHulls.SelectCommand.CommandText = "SELECT Class FROM Hulls WHERE (HullId = " + Trim(Str((iArrLoop + 1))) + ")"                'Populate array                arrHullClass(iArrLoop) = sqlDBDAHulls.SelectCommand.ExecuteScalar                'Redefine SQL Statement                sqlDBDAHulls.SelectCommand.CommandText = "SELECT Design FROM Hulls WHERE (HullId = " + Trim(Str((iArrLoop + 1))) + ")"                'Populate array                arrHullDesign(iArrLoop) = sqlDBDAHulls.SelectCommand.ExecuteScalar                'Populate combobox                ddlHull.Items.Insert(iArrLoop, arrHullClass(iArrLoop) + ":" + arrHullDesign(iArrLoop))            Next iArrLoop
            'Close the database            sqlConnBC.Close()
This all works absolutely fine.
 
In VS2005 there does not appear to be the same data adapter and sql client controls and I am starting to pull my hair out.  this is what I have:
ASP:
<asp:SqlDataSource ID="connSQL" runat="server" CancelSelectOnNullParameter="False" ConnectionString="Data Source=STREETROD;Initial Catalog=DVD;Persist Security Info=True;User ID=sa;Password=xj600f" DataSourceMode="DataReader" ProviderName="System.Data.SqlClient" FilterExpression="ID" SortParameterName="ID"></asp:SqlDataSource>
VB:

'Connect to database and read values
connSQL.ConnectionString = sConnStr
connSQL.SelectCommandType = SqlDataSourceCommandType.Text
connSQL.SelectCommand = "SELECT COUNT('ID') FROM Users"
iCount = connSQL.Select()ReDim sDbUN(iCount - 1)
ReDim sDbPW(iCount - 1)For iLoop = LBound(sDbUN) To UBound(sDbUN)

connSQL.SelectCommand = "SELECT 'UN' FROM Users WHERE 'ID'='" & Str(iLoop + 1) & "'"
sDbUN(iLoop) = connSQL.Select()
connSQL.SelectCommand = "SELECT 'PW' FROM Users WHERE 'ID'='" & Str(iLoop + 1) & "'"
sDbPW(iLoop) = connSQL.Select()
Next
 and all this keeps telling me is that I have not specified any.arguements under System.Web.UI.DataSourceSelectArguments.  I have even tried entering System.Web.UI.DataSourceSelectArguments.Empty to no avail
Can someone please give me a code example that will help me understand this, or at least point me in the right direction?  Or is that I simply HAVE to use a datagrid?
Many thanks.
ProudFoots

View 3 Replies View Related

Calculations In A Datagrid?

Mar 21, 2008

Hello,
I ran into a little problem. My problem is: i need to substract 2 variabeles from 2 different tables in the database 



TitleTimes left todayTimes left


My first excercise!15


My second excercise!19


The fields times left are a calculation... the number of times that the admin entered minus a count in the table scores.
Has anyone an idea how i can solve this?
An example excercise would be great!
Thanks in advance

View 5 Replies View Related

Element In Datagrid?

Mar 22, 2005

please help me to take element in datagrid?

View 1 Replies View Related

SQL Rollup In Datagrid

Jul 13, 2005

Hi,I am attempting to achieve some form of report that needs to make use of sql rollup and display it as follows:Category     Subject Matter1     Subject Matter2     Subject Matter3     No of CasesClubs             Facilities             Sport Facilities          Swimming Pool       3                     SubTotal                                                                     3Events             SBR/AHM                NULL                      NULL                1                     SubTotal                                                                     1                     GrandTotal                                                                     4However, with my sql query, using roll up, it will look like the following which is not correct.Category     Subject Matter1     Subject Matter2     Subject Matter3     No of CasesClubs             Facilities             Sport Facilities          Swimming Pool          3Clubs             Facilities             Sport Facilities             NULL                      3Clubs             Facilities             NULL                         NULL                      3Clubs             Sub Total             NULL                         NULL                      3Events             SBR/AHM             NULL                         NULL                      1Events              SBR/AHM             NULL                         NULL                     1Events             SBR/AHM             NULL                         NULL                      1Events             Sub Total             NULL                         NULL                      1This is the query I am using:<code>select casewhen (grouping(Cat.Description)=1) then 'Grand Total'else Cat.Descriptionend as Category,casewhen (grouping(sub.description)=1) then 'Sub Total'else Sub.descriptionend as SM1,SubSub.Description as SM2, SM.Description as SM3, count(sub.description)from tb_feedbackcase FB left join tb_category Cat on FB.Category_ID = Cat.Category_ID left join tb_subcategory Sub on FB.SubCategory_ID = Sub.SubCategory_IDleft join tb_subsubcategory SubSub on FB.SubSubCategory_ID = SubSub.SubSubCategory_IDleft join tb_SubjectMatterLV3 SM on FB.SM3_ID = SM.SM3_IDwhere fb.commenttype_id in (select commenttypes_id from tb_comment_types where description = @feedback_type)and convert(char(10),feedback_datetime,102) >= convert(char(10),@date_from, 102)and convert(char(10), feedback_datetime, 102) <= convert(char(10),@date_to, 102)group by Cat.Description, Sub.Description, SubSub.Description, SM.Description with rollup</code>How can I change it to reflect more accurately? Please help. Thanks.

View 1 Replies View Related

Pagination Without Datagrid

Mar 13, 2006

I'm working on a website where we're using .Net web services to feed data to a Flash front-end. The site will have a comments section and we want to display 15 or so comments per page with 'back' and 'next' functionalitiy. We'd also like to show the number of pages of comments and highlight the page they're on. The standard stuff that datagrids do so well. How can this be accomplished without a datagrid? There's a good page that explains a number of ways to do this using classic ASP. Some of the solutions they implement I can most likely use with .Net.http://www.aspfaq.com/show.asp?id=2120But I wanted to ask the community. How to paginate without a recordset? Sql Server 2000 back-end, ASP.NET 1.xThanks.

View 3 Replies View Related

Loop Through A Datagrid

Jul 23, 2005

Hi,No I don't want to loop through my dataset ;) I want to loop through mydatagrid to retrieve the values in each cells, but I don't know how todo that ?Can someone help ?thx

View 1 Replies View Related

C# SQL ID Field Datagrid And DataSource

Sep 14, 2006

OK I am a newbie when it comes to lots of .Net so if you answer go slowwww. I have an auto incrementing ID field in a SQL database.This is all displayed to the user in a datagrid control. I add two or three new rows and AcceptChanges.At this point I my ID field displayed on the grid bound tot he SQL ID field is out of Sync. What the #@^%#$&* In fact it looks like the data grid placed in its own numbers by doing some sort of Maxvalue on the column. HELP!  Bob  

View 3 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

DataGrid Updation Problem !!

Jan 19, 2004

Hello all
i am trying to update the database with the DataSet (Updated from the DataGrid) but it is giving the error as
"Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
the code is as follows


public DataSet bindControlToGrid(DataSet dataSet)
{
SqlConnection objConn= null;
SqlCommand objComm = null;
try
{
objConn = new SqlConnection(@"User ID=sa;Password=sa;database=ExtraNet;server=EAGLESEAGLES");

SqlDataAdapter objAdapter=new SqlDataAdapter();
objAdapter.SelectCommand= new SqlCommand("SELECT sUserID,sUserName FROM tblUser WHERE dUserDeActivated IS NULL ORDER BY sUserName,nUsrSerialNo",objConn);
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(objAdapter);
objConn.Open();
DataSet objdataSet= new DataSet("ko");
string d = (dataSet.Tables[0].Rows[0].ItemArray.GetValue(0).ToString());

objAdapter.Fill(objdataSet);
objAdapter.Update(dataSet);
objAdapter.Dispose();
}
catch(Exception ex)
{
string s= ex.Message;
}
finally
{
//objComm.Dispose();
objConn.Close();
}
return dataSet;
}

kindly help

View 1 Replies View Related

Error With Databound Datagrid

May 12, 2005

Help,
 I have a simple app that only has on datagrid that is bound by the typical sqlconnection,sqldataadapter and dataset.  But I keep getting this error:
Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection.Source Error:



Line 55: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Line 56: 'Put user code to initialize the page here
Line 57: SqlDataAdapter1.Fill(DataSet11)
Line 58: DataGrid1.DataBind()
Line 59:
 
WHY :)

View 2 Replies View Related

Datagrid Dataset Problem

Jul 19, 2005

For a datagrid dataset,  I'm trying to take the amount of all the sales by a salesperson in two days and create an alias for sum(saleamount) (which would become allsales) to put the grand total in.
select     thedate, sum(saleamount) as allsales , salesperson, orderID from     transactions WHERE     (thedate IN ('6/1/2005', '6/2/2005')) GROUP BY Salesperson HAVING      SUM(allsales > 0)
I'm getting "invalid syntax near SUM (on the Having clause)" when trying to run this query. And I know there is data in there meeting this criteria.Thanks chumley

View 1 Replies View Related

Fully Editable Datagrid

Nov 10, 2005

I have been trying to formulate a fully editabe datagrid for a couple of days with no luck.  I have used code from 4guys and some other sites and am at the point where I can render the datagrid correctly (as a bouncolumn and template column-textbox) but when I try to update the database it all falls apart.  I am getting "input string was not in a correct format" and the error references ...Dim id as Integer = Convert.ToInt32(sls.DataKeys(dgi.ItemIndex))I suspect the problem lies in the area of primary indexes and such.  The table I am using is a simple two-column table with usernames, passwords.  Username is the primary field. Here is the actual code I am using...<code><%@ Page Explicit="True" Language="VB" Debug="True" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data.OleDb" %><html>
<script runat="server">Dim Connect As OleDbConnection = New OleDbConnectionDim Adapter As OleDbDataAdapter = New OleDbDataAdapterDim DS As DataSet = New DataSetDim ConnectString, SelectStatement As String
Sub Page_Load(Sender As Object, E As EventArgs)
If Not IsPostBack Then SelectStatement = "Select * From Table"ConnectString = "Provider=SQLOLEDB;UID=;PWD=;" & "Data Source=;Initial Catalog=;"
Connect.ConnectionString = ConnectStringAdapter.SelectCommand = New oleDbCommand(SelectStatement, Connect)Adapter.SelectCommand.Connection.OpenAdapter.Fill(DS, "Items")sls.Datasource = DS.Tables("Items")Page.DatabindConnect.Close()End IfEnd Sub
Sub Click(sender As Object, e As EventArgs)  Dim myConnection as New OleDbConnection(ConnectString)Dim updateSQL as String = "UPDATE Table SET password = @Password WHERE Username = @ID"Dim myCommand as New oleDbCommand(updateSQL, myConnection)
Dim dgi as DataGridItemFor Each dgi in sls.Items  'Read in the Primary Key Field  Dim id as Integer = Convert.ToInt32(sls.DataKeys(dgi.ItemIndex))  Dim password as String = CType(dgi.FindControl("txtPass"), TextBox).Text
        'Issue an UPDATE statement...    myCommand.Parameters.Clear()  myCommand.Parameters.Add("@ID", id)  myCommand.Parameters.Add("@Password", password)
  myCommand.ExecuteNonQuery()Next
    End Sub
</script><body><form runat="Server">
<asp:datagrid id="sls" runat="server" AutoGenerateColumns="False" datakeyfield="Username">   <Columns>    <asp:BoundColumn HeaderText="UserName" datafield="Username"/>
         <asp:TemplateColumn HeaderText="Password">      <ItemTemplate>        <asp:TextBox runat="server" id="txtPass" Columns="10"              Text='<%# DataBinder.Eval(Container, "DataItem.Password") %>' />      </ItemTemplate>    </asp:TemplateColumn>
  </Columns> </asp:datagrid><asp:button id="Update" text="Update All" runat="Server" onclick="Click"/></form></body></html></code>Anyone have any idea as to why the id variable (error message above) is causing problems?

View 2 Replies View Related

Capturing Events In A DataGrid

Jul 20, 2005

I'm trying to add functionality to a VB 6 application allowingcustomer service to add a customer number to a new customer.Customers are added to the database by sales personnel, and aprospective customer may have multiple rows due to projected ordersfor multiple products. Customer numbers are assigned when a newcustomer makes their first order.I'm using a DataGrid connected to an ADO Data Control. The datacontrol is connected to a view in SQL Server using the 'distinct'directive (I know it's not updatable) to show only one line per newcustomer. What I wish to do is capture the update event (probablythrough the FieldChangeComplete routine of the data control), manuallyassign the newly entered customer number to all appropriate rows inthe database, and cancel the update event with no notifications.I'm having two problems:1. I can't capture the newly entered customer number. The Textproperty of the DataGrid returns the old value of the cell instead ofthe newly entered value. How do I get the edited value?2. Even though I set adStatus = adStatusCancel in theFieldChangeComplete routine, I get a Microsoft DataGrid Control dialogstating 'Operation was Canceled'. How do I avoid this notification?

View 1 Replies View Related

Must I Display A Column In DataGrid To Reference It?

Oct 11, 2006

Hi,I have a DataGrid whose DataSource is an SQLDataSource. This SQLDataSource references a SQL Server table with an Identity column, named Id. The SQLDataSource has generated an Update statement for me, but this only works if the Id column is selected for display in the DataGrid, and has Visible = True. If not, then the @original_Id parameter to the generated Update statement has a value of Nothing, and the Update has no effect. So is there a way to enable the Update statement to work, without the user having to see the Id column in the DataGrid? Many thanks,Keith.

View 3 Replies View Related

Joined Table -- Display In Datagrid

Apr 20, 2007

Ok here goes.  I have 3 tables, one holds case info, the 2nd holds possible outcome on the charges, and they're joined on a 3rd table (CaseOutComes).  With me so far?  Easy stuff, now for the hard part.
Since there's a very common possiblitly that the Case has multiple charges, we need to track those, and therefore, display them on a datagrid or some other control.  I want the user to be able to edit the info and have X number of dropdowns pertaining to how many ever charges are on the case.  I can get the query to return the rows no sweat, but ...merging them into 1 record (1 row) with mutiple drops is seeming impossible -- I thought about using a placeholder and added the controls that way, but it was not in agreement with what I was trying to tell it .
Any ideas on how to attack this?

View 3 Replies View Related

How To Create A Datagrid For Two No Relationship Tables

Jan 13, 2004

Hi, I am trying to create a create for two table A and table B which have no relationship each time. For TableA, there are 3 columns like ID, APoints1, APoint2. For Table B, there are also 3 columns as ID, Qty, BPoints. There is no internal relationship for these two tables. But there may be same ID inside A and B for some records. Now I want to create a datagrid for displaying the information as :

ID, Sum(A.APoints1 + A.APoints2) - Sum(B.Qty * B.BPoints) WHERE A.ID = B.ID

Please Notice that I can't use directly SQL script as following from table A and table B because there is no relationship for Table A and Table B, otherwise the recult set would be wrong:

Select A.ID, Sum(A.APoints1 + A.APoints2) - Sum(B.Qty * B.BPoints) WHERE A.ID = B.ID group by A.ID


May I know is there solution for it?

Thank you very much!

View 4 Replies View Related

Truncating Date Time In SQL To Use In Datagrid

Apr 1, 2004

I am attempting to bind a smalldatetime field to a datagrid and want to truncate the time off the end of the field so only the date shows up.

Here is the query that I am using:

Select

UserId,
Lastname + ',' + ' ' + Firstname as MembName,
Convert( datetime, Convert( int, MembExpiryDate))

FROM Users


In the datagrid, I have referenced a data element called MembExpiryDate, but with the above query, it no longer recognizes this filed.

If I use

Select

UserId,
Lastname + ',' + ' ' + Firstname as MembName,
MembExpiryDate

It works fine, the date is bound to the grid, but the time is still included obviously.

If I use

Select

UserId,
Lastname + ',' + ' ' + Firstname as MembName,
Convert( datetime, Convert( int, MembExpiryDate)) as ExpiryDate

and reference Expiry date in the datagrid instead, the time is still included.

Any ideas how to write this query to remove the damn time?

Thanks.

Dave

View 4 Replies View Related

Need To Avoid Repeated Data In A DataGrid

Apr 15, 2004

Hi there :)

I am developing a system for my uni course and I am stuck a little problem...

Basically its all about lecturers, students modules etc - A student has many modules, a module has manu students, a lecturer has many modules and a module has many lecturers.

I am trying to get a list of lecturers that run modules associated with a particular student. I am able to get a list of the appropriate lecturers, but some lecturers are repeated because they teach more than one module that the student is associated with.

How can I stop the repeats?

Heres my sql select code in my cs file:

string sqlDisplayLec = "SELECT * FROM student_module sm, lecturer_module lm, users u WHERE sm.user_id=" + myUserid + "" + " AND lm.module_id = sm.module_id " + " AND u.user_id = lm.user_id ";
SqlCommand sqlc2 = new SqlCommand(sqlDisplayLec,sqlConnection);
sqlConnection.Open();
lecturersDG.DataSource = sqlc2.ExecuteReader(CommandBehavior.CloseConnection);
lecturersDG.DataBind();

And here is a pic of my Data Model:
Data Model Screenshot

Any ideas? Many thanks :) !

View 1 Replies View Related

Select Statements To Bind Datagrid

Apr 24, 2004

I want to select 2 fields from two tables inorder to bind my Datagrid...

How can I do that using SQL statement?

Possible to do that with one statement? or i need to create stored procedure?

Can anyone show me sample codes?

View 2 Replies View Related

Display 2 Record Each From 2 Table In Datagrid

Jul 21, 2005

This is my case. I want in my datagrid to display first record from table A and second record from table B. This is because i need to display a price in the column where it will have current price and history price, therefore the first row will be current price and second row will be history price.

This is the output that i trying to do.

Item | Price
-------|---------
A | 2.50 --------> Table A
A | 1.50 --------> Table B

Please let me know if my explanation is not details enough.

Thanks

View 2 Replies View Related

Any One Tell Me The Best Process To Bind The Data To Datagrid?

Jun 2, 2008

Hi,

Any one tell me the best process to bind the data to datagrid?I am using this method,it is taking lot of time to fill data to datagrid.

conn = new SqlCeConnection("Data Source=\sample.sdf; Password =''");
dt = new DataTable();
da = new SqlCeDataAdapter(Quary, conn);
da.Fill(dt);
DataaGrid1.Datasource=dt;

Any one tell the best method?

Regards,
venkat.

View 9 Replies View Related

Transfer Data From Datagrid To Tables In Sql Server

Jul 12, 2006

    Hello, I like to know how to transfer current data displayed in my datagrid into a table in sql server. Any help is much appreciated.Thanks!

View 1 Replies View Related

Updating/getting Values From Datagrid In C# With Variable Parameters

Oct 24, 2006

HiI am new to the world of aspx, .net and C#.In aspx .net 2.0. I am trying to work out how to get a datagrid to perform an update. Using Visual Developer I have successfully added the control and specifed a select statement to return data via my SQLData Source. This works fine. However having specifed the control as editable I would like to perform an update through the datagrid and SQLDatasource. I see in the properties for the SQLDatasource object I can specify my update statement.However I do not understand how to get that update statement to have variable values and how newly entered values from the grid can be placed into these variables when the update takes place. Can someone please point me in the right direction? I have not found the MS doc very illuminating thus far and have not found any examples.Many ThanksT

View 1 Replies View Related

Error Updating Dynamic Datagrid With SQL Server

Jun 29, 2007

Hello, I have a datagrid which is populated with data from an MS SQL server database. When I run an update query it always throws an exception - what is the most likely cause for this given that I am using the code below:  1 public void DataGrid_Update(Object sender, DataGridCommandEventArgs e)
2 {
3 String update = "UPDATE Fruit SET Product = @ID, Quantity = @Q, Price = @P, Total = @T where Product = @Id";
4
5 SqlCommand command = new SqlCommand(update, conn);
6
7 command.Parameters.Add(new SqlParameter("@ID", SqlDbType.NVarChar, 50));
8 command.Parameters.Add(new SqlParameter("@Q", SqlDbType.NVarChar, 50));
9 command.Parameters.Add(new SqlParameter("@P", SqlDbType.NVarChar, 50));
10 command.Parameters.Add(new SqlParameter("@T", SqlDbType.NVarChar, 50));
11 command.Parameters["@ID"].Value = DataGrid.DataKeys[(int)e.Item.ItemIndex];
12 command.Connection.Open();
13
14 try
15 {
16 command.ExecuteNonQuery();
17 Message.InnerHtml = "Update complete!" + update;
18 DataGrid.EditItemIndex = -1;
19 }
20 catch (SqlException exc)
21 {
22 Message.InnerHtml = "Update error.";
23 }
24
25 command.Connection.Close();
26
27 BindGrid();
28 }
 All of the row types in MS SQL server are set to nvarchar(50) - as I thought this would eliminate any inconsistencies in types. Thanks anyone 

View 5 Replies View Related

Displaying Data In Datagrid From A Normalized Set Of Tables

Jul 23, 2007

Ok, I'm fairly new to .NET and even newer to the whole database concept.  But, don't run away yet, I'm no idiot and I shouldn't have too hard of a time understanding your responses if you're kind of enough to give them.  That being said, here's my dilemma:I'm trying to make a database of all the movies I own, the actors in them and the genre (s) they belong to. I have a set of tables that are in the 2NF (I think).  I have a movies table, an actors table, a genres table, and two tables called movies_actors and movies_genres with primary-foreign key relationships to pull it all together (e.g. movie_id 1 has two entries in movies_genres, one for Action and one for Drama). My problem arises that when execute my monster query to pull ALL the data on one movie, I get a row returned for every combination of Genres and Actors in a movie.  Example:movie_id            movie_title            comments            actor_first         actor_last            genre_name1                        Casino                  blah blah            Robert               DeNiro               Action1                        Casino                  blah blah            Robert               DeNiro               Drama1                        Casino                  blah blah            Joe                  Pesci                  Action1                        Casino                  blah blah            Joe                  Pesci                  Drama And here's the query that produced that:1 SELECT movies.movie_title, movies.comments, actors.actor_first,
2 actors.actor_last, genres.genre_name
3 FROM movies INNER JOIN movies_actors ON movies.movie_id = movies_actors.movie_id
4 INNER JOIN actors ON movies_actors.actor_id = actors.actor_id
5 INNER JOIN movies_genres ON movies_genres.movie_id = movies.movie_id
6 INNER JOIN genres ON movies_genres.genre_id = genres.genre_id
So, I want to put all the actors for one movie into the same cell in the datagrid (same with the genres) and still keep it sortable by actor or genre.  Is this possible with the .NET 2.0 datagrid?  Do I have some fundamental misunderstanding of how my tables should be structured?  Am I just really far off and acting like a n00b?

View 9 Replies View Related

(urgent)How Should I Implement A Order In My Datagrid Using SQl Server

Aug 15, 2007

Hi,
    I have created a ASP.net website and i have a page called Investment choices where the user can either type in the data in a text box or there they can select  them from a grid view(called Funds). The Typed data or the selected data goes in to another datagrid(called plans). and i want to implement a display order.
right now when the user adds 6 numbers using the text box and since i seperate them using commas. In Plans datagrid i get the numbers from 1-6. then after words if the user selects the from the Funds gridview it just its adds a number 1.
 
 So how can i have the display order sequentially so if the user types 6 no's it should be  1- 6 and if he selects 2 funds from the gridview it should be 7 and 8. I have a field in the database which is called display order which is a integer. so do u think it makes sense as making that field as an identity field or how should i deal with it.
Any ideas will be appreciated.
Regards,
Karen
 
 
 

View 2 Replies View Related

Filtering Records In Datagrid Using Stored Procedures

Mar 11, 2008

I have created a stored procedure in sql server 2005 which will fetch a particular record based on the value we supply for a column. It is working fine. The same task i need to implement in my web form. I have a textbox in my webform where i will enter the empage which is in the table. Based on the value the record(s) should get displayed in the gridview. How to acheive this. Pls help me with full coding. it is urgent.
Thanx is advance

View 1 Replies View Related

Display Data Using Mxdatagrid Or Datagrid In Webmatrix

Feb 24, 2004

what i'm trying to do is simply display the contents of the sqldata to verify that it works. and it doesn't. i have created a simple database named 'test' and table 'list' with fields: 'name' and 'id'. i have made 3 records as follows:

NAME ID
name1 1
name2 2
name3 3

what i did is connect to the database, click and drag it over to the canvas and codes were generated. if i run it, by default it should show all the contents of the table, correct? well, it isn't. i've tried it using a datagrid and it still doesn't work.

is there an access problem with the database? or, what settings to have to make/change in my sql server? by the way, i have MSDE.


<%@ Page Language="VB" %>
<%@ Register TagPrefix="wmx" Namespace="Microsoft.Matrix.Framework.Web.UI" Assembly="Microsoft.Matrix.Framework, Version=0.6.0.0, Culture=neutral, PublicKeyToken=6f763c9966660626" %>
<script runat="server">

' Insert page code here
'
Function test() As System.Data.IDataReader
Dim connectionString As String = "server='(local)'; trusted_connection=true; database='test'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT [list].* FROM [list]"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

dbConnection.Open
Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

Return dataReader
End Function

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<wmx:SqlDataSourceControl id="SqlDataSourceControl1" runat="server" DeleteCommand="" ConnectionString="server='(local)'; trusted_connection=true; database='Northwind'" SelectCommand="SELECT * FROM [Employees]" UpdateCommand=""></wmx:SqlDataSourceControl>
<wmx:MxDataGrid id="MxDataGrid1" runat="server" OnLoad="MxDataGrid1_Load" DataSource="<%# SqlDataSourceControl1 %>" BorderStyle="None" BorderWidth="1px" DataKeyField="EmployeeID" CellPadding="3" BackColor="White" AllowPaging="True" DataMember="Employees" AllowSorting="True" BorderColor="#CCCCCC" DataSourceControlID="SqlDataSourceControl1">
<PagerStyle horizontalalign="Center" forecolor="#000066" backcolor="White" mode="NumericPages"></PagerStyle>
<FooterStyle forecolor="#000066" backcolor="White"></FooterStyle>
<SelectedItemStyle font-bold="True" forecolor="White" backcolor="#669999"></SelectedItemStyle>
<ItemStyle forecolor="#000066"></ItemStyle>
<HeaderStyle font-bold="True" forecolor="White" backcolor="#006699"></HeaderStyle>
</wmx:MxDataGrid>
<!-- Insert content here -->
</form>
</body>
</html>

View 4 Replies View Related







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