Gridview Select
I am using a GridView which is select enabled. I have another sqldatasource control on my page which will run a SQL query but needs a parameter. This parameter is from a column (EmployeeID) of the selected row in the gridview. In the Sqldatasource control I have specified the parameter source as a control which is Gridview .But I dont know how to point to the EmployeeID column of the selected row.Please help.
View Complete Forum Thread with Replies
Related Forum Messages:
Select Parameters With Gridview
I have a form that has 4 fields to fill in. I have a button that can add these fields to a sql database. I also want to put a button next to the "add" button so you can fill out the same fields and search for those values. Here's what i have so far. I want to select based on the fields, but i'm having trouble with the syntax of the parameters. I also want to add something, so if nothing is filled out in one of those boxes, it retuns back all records for the default value. string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString; SqlConnection myConnection = new SqlConnection(strConnection); String selectCmd = "SELECT * FROM users WHERE firstname = @firstame or lastname = @lastname or office = @office or team = @team"; SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection); myCommand.SelectCommand.Parameters.Add(new SqlParameter("@firstname", SqlDbType.VarChar, 50)); myCommand.SelectCommand.Parameters.Add("@firstname", txtFirstName.Text); myCommand.Parameters.AddWithValue("@lastname", txtLastName.Text); myCommand.Parameters.AddWithValue("@team", dwnTeam.Text); myCommand.Parameters.AddWithValue("@office", dwnOffice.Text); DataSet ds = new DataSet(); myCommand.Fill(ds, "users"); MyDataGrid.DataSource = ds.Tables["users"].DefaultView; MyDataGrid.DataBind();
View Replies !
Changing The SQLDatasource SELECT For A Gridview
I cant seen to change the Select command for a SQL Datasourcetry #1 SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters("ProfileID").DefaultValue = pProfileID SqlDataSourceProfilesThatMatch.SelectParameters("LoggedInUsersZipcode").DefaultValue = pUsersZipCode SqlDataSourceProfilesThatMatch.SelectParameters("ZipDistance").DefaultValue = pDistance NewProfilesThatMatchGridView.DataBind() try #2 SqlDataSourceProfilesToBeMatched.SelectParameters.Clear() SqlDataSourceProfilesThatMatch.SelectCommand = strSQLForSearch SqlDataSourceProfilesThatMatch.SelectParameters.Add("ProfileID", pProfileID) SqlDataSourceProfilesThatMatch.SelectParameters.Add("LoggedInUsersZipcode", pUsersZipCode) SqlDataSourceProfilesThatMatch.SelectParameters.Add("ZipDistance", pDistance) NewProfilesThatMatchGridView.DataBind() No errors but no rows show in the gridview. If I debug and get the value strSQLForSearch and paste it into a new SQL query window I get results. Any ideas???? Thanks
View Replies !
Select Just A Couple Of Rows Into Gridview
I am using a sqlDataSource to read my query and to put the rows into a gridview. Now I want to read just a couple of rows from my query based on a maximum number, also defined in the table. I have absolutely no idea how to do that..for example: I want to view only the 10 most recent subsciptions into my gridview. The subscriptions are stored into tabel Subscriptions which has values id, userid,date. Table Event has a parameter "maximum subscriptions" (which is 10 in my example) I hope it is clear enough?Thank you in advance!BlueiVeinz
View Replies !
Select Command Lost Thus Gridview Shows Nothing
Hi there,I am not sure how many of you have experienced this problem before but here is how to replicate it: Add a GridView, SqlDataSource and Button to a new projectSet the DataSourceID to the SqlDataSource objectSet AllowPaging to True on the GridViewWithin the Button1_Click sub, change the SqlDataSource.SelectCommand to a new Query e.g SELECT * FROM table WHERE ID > 1Run the project Click on another page, i.e. "3" on the GridView SqlDataSource.SelectCommand is now blank(!), thus Gridview displays nothing. Has anyone else found a solution to this annoying issue? Any help is appreciated.Regards
View Replies !
Need Gridview To Display Different Columns Based On New SELECT Statement
I have built an Advanced Search page which allows users to select which columns to return (via checkbox) and to enter search criteria for any of the selected columns (into textboxes). I build the SQL statement from the properties of the controls. Works great. My problem is getting my gridview control to play nicely. At first I used a SqlDataReader and bound the gridview to it, thus giving me the ability to run new SQL statements through it (with different columns each time). Worked nicely. But, per Microsoft, sorting can only be done if the gridview is bound to a datasource control like the SqlDataSource. So I wrote the code to handle sorting. No big deal; worked nicely. But I could not adjust the column widths programmatically unless bound to a datasource control like the SqlDataSource. And could not figure out a work around. So, I decided to use the SqlDataSource. Works great. Except, I cannot figure out how to run a new SELECT statement through the SQLDataSource and have the gridview respond accordingly. If I try to return anything other than the exact same columns defined declaratively in the html, it pukes. But I need to be able to return a new selection of columns each time. For example, first time through the user selects columns 1,2,3,4 – the gridview should show those 4 columns. The second time the user selects columns 2,5,7 – the gridview should those 3 columns (and ONLY those 3 columns). Plus support selection and sorting. I am desperate on this. I've burned 2.5 days researching and testing. Does anyone have any suggestions? Thanks, Brad
View Replies !
Sqldatasource, Does It Select If Not Bound To A Gridview, Formview On The Page?
Using 3.5 If I have a sqldatasource on the page, is it run if it is not bound to a data object like a gridview? Seems like if i want to access the data (like set a label text) from the sqldatasource I have to use code to first create a dataview then pick throught it. This seems like I'm running it twice. I'm new at .net so I dont know how to tell. I don't want to write data select code programatically when I can just through an SDS on the page, but wondered it it ran just because it's on the page.
View Replies !
Want Error Message To Appear When No Database Results Were Returned In GridView, Also Other GridView Issues.
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 Replies !
GridView Based On SQLServerDataSource Using A Select Union Statement, Impacts On Update And Insert?
I have a GridView dispalying from a SQLServerDataSource that is using a SQL Select Union statement (like the following): SELECT FirstName, LastNameFROM MasterUNION ALLSELECT FirstName, LastNameFROM CustomORDER BY LastName, FirstName I am wondering how to create Update and Insert statements for this SQLServerDataSource since the select is actually driving from two different tables (Master and Custom). Any ideas if or how this can be done? Specifically, I want the Custom table to be editable, but not the Master table. Any examples or ideas would be very much appreciated! Thanks, Randy
View Replies !
Gridview
Hi I have a business search box and gridview pair. When the user enters a business name, the search results are displayed. I also generate a "more information" link which takes the user to a new page, passing the business name ("memberId")to this page (see the template field below). The problem I have is if the name contains a QUOTE (') or other special characters. The "memberId" is chopped off at the quote (e.g. "Harry's Store" is passed as "Harry"). Can anyone tell me a way around this please? Is there anything I can do with the Eval method? Kind regards, Garrett <asp:TemplateField HeaderText="More Info"> <ItemTemplate> <a href='member_page.aspx?memberId=<%# Eval("co_name") %>'>more</a> </ItemTemplate> <ItemStyle Font-Bold="False" /> </asp:TemplateField>
View Replies !
???GridView
HiI need to add in gridview control asp code "delete from t1 where id=@id1"how to declare @id1 because the server give me mistake down is the code of asp i use GridView how i can link @id with field there id???Thank u and have a nice daybest regardsthe code if u need it i use c# <ASP:SQLDATASOURCE id=SqlDataSource1 <br ConnectionString="<%$ ConnectionStrings:libraryConnectionString %>" runat="server"><BR></ASP:SQLDATASOURCE></ASP:BOUNDFIELD>
View Replies !
GridView Help
Hi, I use WVD and SQL Express 2005. I have a table “SignIn� that one of fields inserted automatically by getdate() And I have GridView that I use to display this table because I would like take advantage of GridView sorting and paging methods that are embedded in. Currently I display all records at once. My problem is how to make the GridView show today’s records only. I tried this code below, but I get only this message “There are no data records to display.� <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RC1 %>" ProviderName="<%$ ConnectionStrings:RC1.ProviderName %>" SelectCommand="SELECT [student_ID], [SignIn], [SignOut], [Location] FROM [Stud_data] WHERE (CONVERT(VARCHAR(10),[SignIn],101) = @SignIn)"> <SelectParameters> <asp:QueryStringParameter Name="SignIn" QueryStringField="Format(Now, "M/dd/yyyy")" Type="DateTime" /> </SelectParameters> </asp:SqlDataSource> Help Please!
View Replies !
Gridview And Sqldatasource
i have a gridview which is bound to sqldatasource. i have a delete button in the gridview. I have written code for "deleting" a record in app_code directory. now iam not using "deletecommand" of sqldatasource but on the click of "delete" link i want to call the procedure in the app_code. Any ideas on how to do it.??
View Replies !
Help!!! Gridview Binding
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 Replies !
Gridview Sql Timeout
I have a simple gridview displaying data from an MSSQL server 2005. Every now and then I get a sql timeout error. Listed below. Can anyone explain why I am getting this error? The connection pool is 100 and the timeout is set to 360. I have checked to current connections in SQL and they never max over 23. There are not locks in SQL when the problem occurs. The query is a stored procedure in sql and when sent sample data it normally takes about 5 seconds. Event code: 3005 Event message: An unhandled exception has occurred. Event time: 12/3/2007 9:46:37 PM Event time (UTC): 12/4/2007 3:46:37 AM Event ID: 140501f9a7744dfea2e445ed00939e44 Event sequence: 42 Event occurrence: 1 Event detail code: 0 Application information: Application domain: /LM/W3SVC/1/ROOT-1-128412128787656250 Trust level: Full Application Virtual Path: / Application Path: c:inetpubwwwroot Machine name: DD-MAIN Process information: Process ID: 5544 Process name: w3wp.exe Account name: NT AUTHORITYNETWORK SERVICE Exception information: Exception type: SqlException Exception message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Request information: Request URL: http://localhost/Search_DG.aspx?SearchWord=1212 Request path: /Search_DG.aspx User host address: 10.10.10.1 User: Is authenticated: False Authentication Type: Thread account name: NT AUTHORITYNETWORK SERVICE Thread information: Thread ID: 1 Thread account name: NT AUTHORITYNETWORK SERVICE Is impersonating: False Stack trace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.SetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.WebControls.GridView.get_Rows() at Install_DG.Page_Load(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) Custom event details: For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
View Replies !
SQL OutputCache GridView
I'm trying to cache the contents of a gridivew unless another page, or sorting method are being called. I tried to use the VaryByParam method, but I'm not having any luck, I keep getting the same page sent back to me. Here's what my code looks like. <%@ OutputCache Duration="180" VaryByParam="Page$, Sort$" %> Any help would be appreciated. Stephen
View Replies !
Gridview Question
Sqldatasources are used for a dropdownlist and a gridview. How can the dropdownlist selection refresh the gridview? This is done programmatically in ASP.NET 1.1 code behind. Can it be done in ASP.NET 2.0 without code behind? Thanks.
View Replies !
GridView...Problem
I m creating the project in asp.net using c# and vb languages in 2005.I have used the asp standard controls(with table<td><tr>) and gridview to design the form.I m using sqldatasource to insert and update data from sql server 2005.I have written the following code <script runat="server"> Private Sub Page_Load() If Not Request.Form("SUBMIT") Is Nothing Then srccompany.Insert() End If End Sub</script> <asp:SqlDataSource id="srccompany" SelectCommand="SELECT * FROM companymaster" InsertCommand="INSERT companymaster(companyname) VALUES (@companyname)" UpdateCommand="UPDATE companymaster SET companyname=@companyname WHERE companyid=1" DeleteCommand="DELETE companymaster WHERE companyname=@companyname" ConnectionString="<%$ ConnectionStrings:companymaster %>" Runat="server"></asp:SqlDataSource> <asp:GridView id="GridCompanyMaster" DataSourceID="srccompany" Runat="server" />Please help me to insert the data in sql server.i m not been able to insert the data is there any problem in coding..Also i m not been able to edit the data and store back to sql server.Only i can do is i can view the contents in gridview Please give me some tips
View Replies !
Gridview Search
I tried doing a text box search within Gridview. My code are as follows. However, when I clicked on the search button, nothing shown. Any help would be appreciated. I'm using an ODBC connection to MySql database. Could it be due to the parameters not accepted in MySql? Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) SqlDataSource1.SelectCommand = "SELECT * FROM carrier_list WHERE carrierName LIKE '%' + @carrierName + '%'" End Sub Sub doSearch(ByVal Source As Object, ByVal E As EventArgs) GridViewCarrierList.DataSourceID = "SqlDataSource1" GridViewCarrierList.DataBind() End Sub HTML CODES (Snippet) <asp:Button ID="btnSearchCarrier" runat="server" onclick="doSearch" Text="Search" /> ' Gridview<asp:GridView ID="GridViewCarrierList" runat="server" DataSourceID="SqlDataSource1" > </asp:GridView> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM carrier_list"> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"> <SelectParameters> <asp:ControlParameter ControlID="txtSearchCarrier" Name="carrierName" PropertyName="Text" Type="String"></asp:ControlParameter> </SelectParameters> </asp:SqlDataSource>
View Replies !
Gridview And DropDownList
Hello:I have add a DropDownList to my GridView and binded the dropdownlist to a field from a select statement in the SQLDataSource. I have EnabledEditing for my GridView. The GridView is populated with information from the select statement. Some of the information returned from the select statement is null. The field where the dropdownlist is binded it is null in some cases and does not have a value that is in the dropdownlist so I get and error when I attempt to do an update. 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.Parameter name: value Is there a way to get around this besides initializing all the columns in the table that are going to be binded to a dropdownlist to a value in the dropdownlist?
View Replies !
Gridview Sorting
I have a gridview that has AllowSorting="true" however I need to implement my own sorting because I have DateTime and Integer data types in several of the columns and I don't want an int column sorted like 1,12,2,23,3,34,4,45,5,56, etc. So, I've added SortParameterName="sortBy" and adjusted my stored procedure to accept this. For only ASC sorting, I've got ORDER BY CASE WHEN @sortBy='' THEN DateCreated END, CASE WHEN @sortBy='DateCreated' THEN DateCreated END and so on. However, columns can also be sorted with DESC. I tried CASE WHEN @sortBy='DateCreated DESC' THEN DateCreated DESC END, but I get a syntax error on DESC. How can I do this?
View Replies !
Datatable From Gridview
hi all 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 " thanks
View Replies !
Specifying Updateparameters In Gridview
Where exactly are the updateparameters of a gridview picked up from? I have created 2 very similar gridviews and given the updateparameters the same names as in my edititemtemplates. Yet this method has worked for 1 gridview and failed for the second gridview. Here is my gridview : <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:XConnectionString %>" SelectCommand="ViewForecast" SelectCommandType="StoredProcedure" DeleteCommand="DeleteForecast" DeleteCommandType="StoredProcedure" UpdateCommand="UpdateForecast" UpdateCommandType="StoredProcedure"> <DeleteParameters> <asp:Parameter Name="ForecastKey" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ForecastKey" Type="Int32" /> <asp:Parameter Name="CompanyKey" Type="Int64" /> <asp:Parameter Name="ForecastType" Type="Char" /> <asp:Parameter Name="MoneyValue" Type="Double" /> <asp:Parameter Name="ForecastPercentage" Type="Double" /> <asp:Parameter Name="DueDate" Type="DateTime" /> <asp:Parameter Name="UserKey" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:XConnectionString %>" SelectCommand="GetCompaniesByUser" SelectCommandType="StoredProcedure"> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:XConnectionString %>" SelectCommand="GetForecastTypes" SelectCommandType="StoredProcedure"> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:XConnectionString %>" SelectCommand="GetForecastPercentages" SelectCommandType="StoredProcedure"> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" SkinID="Grey" AutoGenerateColumns="false" DataKeyNames="ForecastKey" AllowSorting="true" OnRowDataBound="GridView1_RowDataBound" EditRowStyle-CssClass="dgedit" OnRowUpdated="GridView1_RowUpdated" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting"> <Columns> <asp:TemplateField HeaderText="Key" SortExpression="ForecastKey"> <ItemTemplate> <asp:Label ID="lblForecastKey" Text='<%# Bind("ForecastKey") %>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Company" SortExpression="CompanyName"> <ItemTemplate> <asp:Label ID="lblCompany" Text='<%# Eval("CompanyName") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlCompanyName" DataSourceID="SqlDataSource2" Runat="Server" DataTextField="CompanyName" DataValueField="CompanyKey" SelectedValue='<%# Bind("CompanyKey") %>' /> </EditItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Forecast Type" SortExpression="ForecastDescription"> <ItemTemplate> <asp:Label ID="lblForecastType" Text='<%# Eval("ForecastDescription") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlForecastType" DataSourceID="SqlDataSource3" Runat="Server" DataTextField="ForecastDescription" DataValueField="ForecastType" SelectedValue='<%# Bind("ForecastType") %>' /> </EditItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Value (£)" SortExpression="MoneyValue"> <ItemTemplate> <asp:Label ID="lblMoneyValue" Text='<%# Eval("MoneyValue", "{0:#,###.00}") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtMoneyValue" Text='<%# Bind("MoneyValue", "{0:#,###.00}") %>' runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtMoneyValue" Display="None" ErrorMessage="Please enter a Value" /> <asp:CompareValidator ID="CompareValidator1" runat="server" Display="None" ErrorMessage="Value must be numeric" ControlToValidate="txtMoneyValue" Type="Double" Operator="DataTypeCheck"></asp:CompareValidator> </EditItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Probability (%)" SortExpression="ProbabilityValue"> <ItemTemplate> <asp:Label ID="lblProbability" Text='<%# Eval("ForecastPercentage") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlForecastPercentage" DataSourceID="SqlDataSource4" Runat="Server" DataTextField="ForecastPercentageDescription" DataValueField="ForecastPercentage" SelectedValue='<%# Bind("ForecastPercentage") %>' /> </EditItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Value (£) x Probability (%)" SortExpression="ProbabilityValue"> <ItemTemplate> <asp:Label ID="lblProbabilityValue" Text='<%# Eval("ProbabilityValue", "{0:#,###.00}") %>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Due Date" SortExpression="DueDate"> <ItemTemplate> <asp:Label ID="lblDueDate" Text='<%# Eval("DueDate", "{0:dd/MM/yyyy}") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtDueDate" Text='<%# Bind("DueDate", "{0:dd/MM/yyyy}") %>' runat="server"></asp:TextBox> <!--or use this in SQL : Select Convert(VarChar(10), GetDate(), 103)--> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDueDate" Display="None" ErrorMessage="Please enter a Due Date" /> <asp:CompareValidator ID="CompareValidator2" runat="server" Display="None" ErrorMessage="Please enter a valid Due Date in format dd/mm/yyyy" ControlToValidate="txtDueDate" Type="Date" Operator="DataTypeCheck"></asp:CompareValidator> </EditItemTemplate> <ItemStyle Height="24px" Width="65px" /> </asp:TemplateField> <asp:TemplateField HeaderText="Last Edit Date" SortExpression="LastEditDate"> <ItemTemplate> <asp:Label ID="lblLastEditDate" Text='<%# Eval("LastEditDate", "{0:dd/MM/yyyy}") %>' runat="server"></asp:Label> </ItemTemplate> <ItemStyle Height="24px" Width="50px" /> </asp:TemplateField> <asp:CommandField ShowEditButton="True" ButtonType="Link" ShowCancelButton="True" UpdateText="Update" EditText="Edit" CancelText="Cancel" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="DeleteButton" CommandArgument='<%# Eval("ForecastKey") %>' CommandName="Delete" runat="server"> Delete</asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> And here is my stored proc : CREATE procedure dbo.UpdateForecast ( @ForecastKey int, @CompanyKey bigint, @ForecastType char(1), @MoneyValue float, @ForecastPercentage float, @DueDate datetime, @UserKey int) as update Forecastset CompanySiteKey = @CompanyKey,MoneyValue = @MoneyValue,Probability = @ForecastPercentage,ForecastType = @ForecastType,InvoiceDate = @DueDate,UserKey = @UserKeywhere ForecastKey = @ForecastKeyGO Can anybody with more experience of using gridview please tell me where I am going wrong? Cheers, Mike
View Replies !
GridView - SqlDataSource
I have created a GridView that uses a SqlDataSource. When I run the page it does not pull back any data. However when I test the query in the SqlDataSource dialog box it pulls back data. Here is my GridView and SqlDataSource: <asp:GridView ID="Results" runat="server" AllowPaging="True" AllowSorting="True" CellPadding="2" EmptyDataText="No records found." AutoGenerateColumns="False" Width="100%" CssClass="tableResults" PageSize="20" DataSourceID="SqlResults" > <Columns> <asp:BoundField DataField="DaCode" HeaderText="Sub-Station" SortExpression="DaCode" > <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="DpInfo" HeaderText="Delivery Point" SortExpression="DpInfo" > <HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" /> <ItemStyle CssClass="tdResults" /> </asp:BoundField> <asp:HyperLinkField DataNavigateUrlFields="CuCode,OrderID" DataNavigateUrlFormatString="TCCustDetail.asp?CuCode={0}&OrderID={1}" DataTextField="OrderID" HeaderText="Order No" SortExpression="OrderID"> <ItemStyle CssClass="tdResults" HorizontalAlign="Center" /> <HeaderStyle CssClass="tdHeaderResults" HorizontalAlign="Center" /> </asp:HyperLinkField> <asp:BoundField HeaderText="Order Date" SortExpression="OrderDate" DataField="OrderDate" > <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="ReqDeliveryDate" HeaderText="Req Delivery Date" SortExpression="ReqDeliveryDate" > <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="StatusDate" HeaderText="Status Date" SortExpression="StatusDate"> <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="ManifestNo" HeaderText="Manifest No" SortExpression="ManifestNo"> <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="CustomerPO" HeaderText="P.O. No" SortExpression="CustomerPO"> <ItemStyle HorizontalAlign="Center" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Center" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class"> <ItemStyle HorizontalAlign="Left" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" /> </asp:BoundField> <asp:BoundField DataField="OrderStatus" HeaderText="Order Status" SortExpression="StatusSort"> <ItemStyle HorizontalAlign="Left" CssClass="tdResults" /> <HeaderStyle HorizontalAlign="Left" CssClass="tdHeaderResults" /> </asp:BoundField> </Columns> <HeaderStyle ForeColor="White" HorizontalAlign="Left" /> <AlternatingRowStyle CssClass="tdResultsAltRowColor" /> </asp:GridView> <asp:SqlDataSource ID="SqlResults" runat="server" ConnectionString="<%$ ConnectionStrings:TransportationConnectionString %>" SelectCommand="GetOrderSummaryResults" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:Parameter DefaultValue="10681" Name="CuCode" Type="String" /> <asp:Parameter DefaultValue="" Name="DaCode" Type="String" /> <asp:Parameter DefaultValue="" Name="DpCode" Type="String" /> <asp:Parameter DefaultValue="" Name="OrderID" Type="String" /> <asp:Parameter DefaultValue="" Name="ManifestNo" Type="String" /> <asp:Parameter DefaultValue="" Name="PONo" Type="String" /> </SelectParameters> </asp:SqlDataSource> I can get it to fill with data by manually filling the GridView without using a SqlDataSource but then I cannot get the sorting to work when I do it that way. Actually not sure if the sorting will work this way either as I cannot get it to fill with data. Any ideas would be much appreciated.
View Replies !
Searching A Gridview In ASP.NET 2.0
Hello,How do I search through the gridview? Would I do this at the sqldatasourcelevel?I figured that I sould search with the datatable.select but how do I accessthe datatable of the sqldatasource?I am using ASP.NET 2.0 with VB.Thanks for your helpJ
View Replies !
Editing In The GridView
Hi I want to Enable Editing in the GridView but there is a problem the GridView take its data from 2 tables and I do this by the build query so I can't choose the " advance " button and check for enable update and delete statements and when I try to build the update query in the update tap I don't know what to write in the "new value" column so how can enable editing in the GridView that take from 2 tables??????? please help me and thanks
View Replies !
Crosstable In Gridview
First of all I like to say hello. Its my first post and I hope somebody will be so kind and help me. I have 3 tables in a database. They look like follow: 1. Table called State: ------------------------------ Id Caption 2. Table called Craft: ----------------------------- Id Caption 3. Table called Wage: ------------------------------- StateId CraftId Wage (decimal) What I'm trying to do is, create a crosstable like the following and display it in a Gridview Texas California Washington ... digging 25,60 31,42 ... masonry works 40.66 ... ... So, the columns come from table State, the row titles come from Craft and the values from Wage. After changing the values I want to save values back to Wage. I started to build this crosstable but faced several problems. For example I dont know how to set a Caption on the left side of each row (Caption of table Craft). And even worse, how shall I update table Wage if there are no Id's in the crosstable anymore to make sure that I save the Value on the right place back in table Wage. It would be very kind if somebody has a solution or a method of resolution.
View Replies !
Do Not Include Certain Rows Into Gridview
I want to retrieve some data in my gridview using a sqldatasource. Here's the idea. My Gridview contains events. A user can subscribe into one of them. When he subscribes, the event must be removed in the gridview. So when there is a subscription from that certain user for that event, it may not appear. Here's my not working code..SELECT Event.EventID,Event.name, Event.LocationID, Event.Date, Event.StatusFROM Shift INNER JOIN Event ON Shift.EventID = Event.EventID INNER JOIN Subscription ON Shift.ShiftID = Subscription.ShiftIDWHERE (Subscription.UserID <> @UserID) Greetz
View Replies !
GridView Update - Validation?
design view is great, just drag on a gridview make it link to my database and poof there is all my data! I can even click the "allow editting button" and poof I can edit my data. But how do assign validation rules? because atm if someone tries to edit my name field at puts in "asdfasdkfhdsgasdgaga" which is too long, clicks update it goes to a horrible error page. How can I catch these errors and make a nice message instead? Thanks very much
View Replies !
Sql Data Dependency With GridView
Hi,I want to add Sql data dependency in GridView. Whenever any changes in database, same will be reflected in Grid. but this should work in both Sql server 2000 and sql server 2005. And when we click on "Pause" button it should stop refreshing. PAUSE Index First name Last Name Address 1 Xyz Abc Asdf, asdf 2 Pqr Asd Sdsa, asad Is there any way to fulfill this kind of requirement? Please suggest me optimal solution to do this.Regards,Mustakim Mansuri
View Replies !
Gridview To Database Rpoblem?
HiI have page where gridview is loaded from the Excel sheet and when the button is clicked it must insert those values in to the table and ........the code for loading the gridview from the excel if working fine but when i click on the Insert button i am getting the errors the code behind for button is as follows: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click ' Dim constr As String = "...." 'your connection string ' Dim connection As SqlConnection = New SqlConnection(constr) Dim i As Integer Dim ia As Integer = ds.Tables("table").Rows.Count - 1 For i = 0 To ia Dim one As String = ds.Tables("table").Rows(i)("Column1") Dim two As String = ds.Tables("table").Rows(i)("Column2") Dim three As String = ds.Tables("table").Rows(i)("Column3") Dim four As String = ds.Tables("table").Rows(i)("Column4") Dim five As String = ds.Tables("table").Rows(i)("Column5") Dim six As String = ds.Tables("table").Rows(i)("Column6") Dim seven As String = ds.Tables("table").Rows(i)("Column7") Dim eight As String = ds.Tables("table").Rows(i)("Column8") Dim nine As String = ds.Tables("table").Rows(i)("Column9") Dim ten As String = ds.Tables("table").Rows(i)("Column10") 'get every cell content of this row like the above line ' Dim sqlsel As String = "insert into table('ID') values('" + one + "')" Dim cmdSavegrd As OdbcCommand = New OdbcCommand("INSERT INTO gd_master VALUES( " & one & ",'" & two & "', '" & three & "'," & four & ",'" & five & "'," & six & "," & seven & ",'" & eight & "'," & nine & ",'" & ten & "')", con) 'Dim sdc As SqlCommand = New SqlCommand(sqlsel, con) ' sdc.CommandType = CommandType.Text con.Open() 'sdc.ExecuteNonQuery() cmdSavegrd.ExecuteReader() con.Close() Next End Sub The Error i am getting is as follows ........."Object reference not set to an instance of an object. " Please can any help me in this?>?
View Replies !
Calendar Filtering In Gridview
I have 2 dropdownlist and a gridview. The dropdownlists filter the gridview, but now I have added two calendars and two textboxes. After user makes selections from the calendar the text boxes are populated with the dates. How do I add this to the following select parameter so that the filtering/querying works properly? (what I have here does not work in terms for the dates, but dropdownlists filter when I remove the dates section):<asp:SqlDataSource ID="DATA" runat="server" ConnectionString="<%$ ConnectionStrings:DATA_Connection %>" SelectCommand="SELECT * FROM [atable] WHERE(afield=@param1 or @Param1='Select something' or((CONVERT(char(10), adate, 101)>=@param3 AND CONVERT(char(10), bdate, 101)<=@param4)) AND(bfield=@Param2 OR @Param2='Select something' or((CONVERT(char(10), adate, 101)>=@param3 AND CONVERT(char(10), bdate, 101)<=@param4))" UpdateCommand="Update atable set afield=@afield, bfield=@bfield where id=@ID" > <selectParameters> <asp:controlparameter name="param1" controlid="DropDownList1" PropertyName="SelectedValue" type="String" /> <asp:controlparameter name="param2" controlid="DropDownList2" PropertyName="SelectedValue" type="String" /> <asp:ControlParameter Name="param3" ControlID="Textbox1" PropertyName="Text" Type="string" /> <asp:ControlParameter Name="param4" ControlID="Textbox2" PropertyName="Text" Type="string" /> </selectParameters>
View Replies !
SqlDataSource, GridView && A Button
hi .. i have a SqlDataSource, GridView & a Button .. i want to increase the condition in the "SelectCommand" below by one everytime i click the button .. i mean to be like that ID < 8 instead of ID < 7 so, the GridView will show 7 ID's instead of 6 .. and it will increase everytime i hit the button<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connectionstring %>" SelectCommand="SELECT * FROM [table1] WHERE ID < 7"> </asp:SqlDataSource>
View Replies !
Updaing A GridView At Runtime
Hi I am binding SQLdatasource with the Gridview at runtime that works fine, but i have mentioned the update command as well, but grid is not updating, there is no error, but after clicking update, no thing happens and grid returns to last state. Part of code is : void btnshowdata_click(){ SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure; SqlDataSource1.SelectCommand = "dbo.getAllOutstanding"; SqlDataSource1.UpdateCommand = "UPDATE SPS_Oustandings SET Status = @Status, Comments = @Comments WHERE (Inv_No = @Inv_no)"; grid.DataBind(); } datasource is already attached to grid, but its select query is chaning at button click. At design time binding update works but when i click the button binding(select quesry) is changed, after that update is not working. Any help? Thanks
View Replies !
Gridview Refresh After Update
Hi All, I am new to development of asp. I have an SQLDataSource set as the data source for a grid view. When I click on the edit link in the Gridview, change the data, and click update, the old data is still displayed in the row. I found exact same issue as here -- http://forums.asp.net/thread/1217014.aspx Solution in the above thread is to add this { if (reader != null) reader.Close(); } conn.Close(); How do I apply above solution in my situation ? I am updating through stored procedure.and don't have code at background. My code is Datasource : <asp:SqlDataSource ID="ds" runat="server" ConnectionString="<%$ ConnectionStrings:ds %>" CancelSelectOnNullParameter="False" ProviderName="<%$ ConnectionStrings:ds.ProviderName%>" UpdateCommand="usp_save" UpdateCommandType="StoredProcedure" EnableCaching="False"> <UpdateParameters> <asp:Parameter Name="field1" Type="String" /> <asp:Parameter Name="field2" Type="String" /> <asp:Parameter Name="field3" Type="String" /> <asp:Parameter Name="field4" Type="String"/> <asp:ControlParameter Name="field5" Type="String" ControlID = "label7" /> </UpdateParameters>
View Replies !
Deleting And Updating From Gridview
Hi,I made a gridview, and I am trying to make it so when the user deletes a row, values in other tables update. I used the following source code: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" DeleteCommand="DELETE FROM [Transactions] WHERE [TransactionID] = @TransactionID AND UPDATE [items] SET Quantityavailable, numtaken VALUES Quantityavailable + 1, numtaken - 1 WHERE ([Itemid] = @Itemid) " It gives the error that Quantityavailable is not a SET type?Thanks if you can suggest a remedy! Jon
View Replies !
Using Textbox Value In GridView SelectCommand
I'm trying to create a simple search against a SQL Database. I setup a TextBox and a GridView, I simply need the contents of the textbox to be used on databind() in my SQL select statement. Seems like it should be a simple thing to do, any guidance is appreciated! Here is my code: <%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="IP Tracker - Search" EnableSessionState="True" %> <script runat=server>Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Search_GridView.DataBind() End Sub </script> <asp:Content ID="Content1" ContentPlaceHolderID="MasterContent" Runat="Server"> <br /> <strong>Search for IP</strong><br /> <br /> <input id="SearchBox" type="text" /><br /> <asp:Button ID="Button1" runat="server" Text="Please Work..." onclick="Button1_Click"/><br /> <br /> <asp:GridView ID="Search_GridView" runat="server" DataSourceID="SqlDataSource1" EmptyDataText="No Records Match"> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:IP_TrackerConnectionString %>" SelectCommand="SELECT * FROM [AddressTable] WHERE ([IPAddress] LIKE '%' + SearchBox.text + '%')"> <SelectParameters> <asp:FormParameter FormField="SearchBox" Name="IPAddress" Type="String" /> </SelectParameters></asp:SqlDataSource> </asp:Content>
View Replies !
Sort Gridview Using Dataset
Hi, I am populating a gridview from a dataset. How to i enable sorting? I get the following error: "The GridView 'imgGrid' fired event Sorting which wasn't handled. " Here is my VB: Dim ds As New DataSet Dim param = CType(Request.QueryString("record"), String) Dim da As SqlClient.SqlDataAdapter Dim strSQL As String strSQL = "Select * from myimages where version_id=" & param Dim connString As String = "SQL Data Source" da = New SqlClient.SqlDataAdapter(strSQL, connString) da.Fill(ds) ds.Tables(0).Columns.Add("imgFile") For Each tempRow As DataRow In ds.Tables(0).Rows tempRow.Item("imgFile") = ("grabimage.aspx?id=" & tempRow.Item("id")) Next imgGrid.DataSource = ds imgGrid.DataBind() imgGrid.Sort("title", SortDirection.Ascending) Thanks, Bones
View Replies !
Binding Gridview From Two Different Tables
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 Replies !
Gridview && SQL Data Source
I have a few Stored procedures that return values, some need parameters passing and others don't. Up to now to access that data in a Web App I have called this procedure using VB after seting up a data block etc. However I notice that the Web Developer express edition has some tools that look like they should help. I have used the in-built tools to create a SQL data source linked to a details view. I then specified that this should connect to my database (sql2005 hosted) and then specified Custom SQL or Stored procedure. From the drop down I can then select the SP that purely returns values. When I try to test this query I get an error to say that the query did not return any data tables. Is there a way to get values returned from a SP in this way? Regards Clive
View Replies !
Ajax Toggle Within A Gridview
Ive got a table of items which holds the privacy settings for each user. The items can either be the value 1 = Yes ,or 0 = No. Is it possible to bind these two options to a checkbox? I tryed to simply bind it to the checkboxes "checked" property, But it errored. Does anyone know how to bind an int feild to a checkbox? cos in the long run I want to add ajax toggle items to the checkboxes, but i was also wondering why that errored, but i think its cos i did my binding wrong. thanks si!
View Replies !
Filling Gridview From Code
hello, i'd need a little help with filling GridViewsi browsed over like 10 search pages, but couldnt find any which would solve my problem.so in my ajax project i made a testing page pulled a gridview (GridView1) on it with a fhew buttons and textboxes.i need to fill the gv from code so my websie.asp.cs looks like this 1 protected void Page_Load(object sender, EventArgs e)2 {3 4 5 string connstr = "Data Source=.;database=teszt;user id=user;password=pass";6 SqlConnection conn = new SqlConnection(connstr);7 SqlCommand comm = new SqlCommand("select * from users", conn);8 conn.Open();9 SqlDataReader reader;10 reader = comm.ExecuteReader();11 if (reader.HasRows)12 {13 GridView1.DataSource = reader;14 GridView1.DataBind();15 }16 reader.Close();17 conn.Close();18 comm.Dispose();19 } so i load the page and there's no gridview on the page at all, nor an error msg, the connection and the database/table is fine.any suggestions on what am i doing wrong? and i also like to know if there would be any problem with using this on a tabcontrol/tabthankyou
View Replies !
GridView Delete Function
This is killing me. I've searched the forums for hours and can't find the answer. My SQLDataSource is working fine except when I want to delete. I've allowed the delete function to be shown on the gridview. This is my SQLDataSource: <asp:SqlDataSource ID="IndexDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:IndexConnectionString %>" SelectCommand="SELECT * FROM [Index] WHERE (Type LIKE '%' + @SearchText2 + '%') OR (Product LIKE '%' + @SearchText2 + '%') OR (Version LIKE '%' + @SearchText2 + '%') OR (Binder LIKE '%' + @SearchText2 + '%') OR (Language LIKE '%' + @SearchText2 + '%') OR (CDName LIKE '%' + @SearchText2 + '%') OR (Details LIKE '%' + @SearchText2 + '%') OR (ISOLink LIKE '%' + @SearchText2 + '%')" DeleteCommand="DELETE FROM [Index] WHERE [ID] = @original_ID" UpdateCommand="UPDATE [Index] SET Type = @Type, Product = @Product , Version = @Version, Binder = @Binder, Language = @Language, CDName = @CDName, Details = @Details, ISOLink = @ISOLink WHERE ID = @ID"> <SelectParameters> <asp:ControlParameter Name="SearchText2" Type="String" ControlID="SearchText2" PropertyName="Text" ConvertEmptyStringToNull="False" /> </SelectParameters> <DeleteParameters> <asp:Parameter Name="original_ID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="Type" /> <asp:Parameter Name="Product" /> <asp:Parameter Name="Version" /> <asp:Parameter Name="Binder" /> <asp:Parameter Name="Language" /> <asp:Parameter Name="CDName" /> <asp:Parameter Name="Details" /> <asp:Parameter Name="ISOLink" /> </UpdateParameters> </asp:SqlDataSource> It doesn't give me an error if I click delete but it doesn't delete the record. I've tried changing the DeleteParameter to <asp:Parameter Name="ID" Type="Int32" /> but it gives me the error "Must declare the scaler variable of '@ID'"... I saw in this post http://forums.asp.net/p/1077738/1587043.aspx#1587043 that the answer was that "The variable you have declared in the definition of the proc is different from the variable you are using in the WHERE clause." when they are both the same. Thanks for any help.-Brandan
View Replies !
Paging With Gridview And ObjectDataSource
I have a problem with efficiently paging with gridview and objectdatasoruce. I have GetPosts1(startRowIndex, maximumRow, topic_id) and GetPostsCount(topic_id). I tested each procedure and each are working correctly. The problem is with the controls. Here is the code for the controls. <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames DataSourceID="ObjectDataSource2"> <Columns> <asp:BoundField DataField="RowNumber" HeaderText="RowNumber" SortExpression="RowNumber" /> <asp:BoundField DataField="post_id" HeaderText="post_id" SortExpression="post_id" /> <asp:BoundField DataField="post_subject" HeaderText="post_subject" SortExpression="post_subject" /> <asp:BoundField DataField="post_text" HeaderText="post_text" SortExpression="post_text" /> <asp:BoundField DataField="post_time" HeaderText="post_time" SortExpression="post_time" /> <asp:BoundField DataField="topic_id" HeaderText="topic_id" SortExpression="topic_id" /> <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" /> <asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" OldValuesParameterFormatString="original_{0}" EnablePaging="True" SelectMethod="GetPosts1" SelectCountMethod="GetPostsCount" TypeName="PostsTableAdapters.discussions_GetPostsTableAdapter"> <SelectParameters> <asp:QueryStringParameter DefaultValue="48" Name="topic_id" QueryStringField="t" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> When I run the page, I get "A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll" and then "The thread '<No Name>' (0xbe0) has exited with code 0 (0x0)." Could the problem be with null or empty values in the returned data?
View Replies !
Paging With Gridview And ObjectDataSource
I'm trying to effecinty page through many rows of data with the gridview and objectdatasource. I'm having trouble. I'm using a table adapter with predefined counting and select methods. I have tested all the methods and they all work properly. But when I configure the object datasource to use the table adapter, and set the gridviews datasrouce, the page doesn't load and I wind up getting "time out". Any help? <asp:GridView ID="GridView1" runat="server" AllowPaging="True" DataSourceID="objTopics"> <Columns> <asp:BoundField DataField="topic_title" /> </Columns> <EmptyDataTemplate> <p>NOTHING HERE</p> </EmptyDataTemplate> </asp:GridView> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" EnablePaging="True" OldValuesParameterFormatString="original_{0}" SelectMethod="GetTopics" SelectCountMethod="GetTopicsRowCount" TypeName="TopicsTableAdapters.discussions_GetTopicsSubSetTableAdapter"> <SelectParameters> <asp:Parameter DefaultValue="1" Name="startRowIndex" Type="Int32" /> <asp:Parameter DefaultValue="10" Name="maximumRows" Type="Int32" /> <asp:Parameter DefaultValue="1" Name="board_id" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource>
View Replies !
Maually Update Gridview
I want to write the results of a checkbox to my database, but I am stuck on the syntax? Here's what I have so far, could somebody pleae help., my aim is to not show a line when checkbox ticked, not to actually delete the record from the database Hi, The problem that I have now is that yes I want to delete from gridview, but I still want the old record to be in database ,not deleted. Does anybody know how I can evaluate my checkbox, and update to the database the results of the checkbox,I am not sure of the update syntax?string strsql = "update * from jobs order by ID asc"; SqlConnection conn = new SqlConnection(ConnectionString); SqlDataAdapter ad = new SqlDataAdapter(strsql, conn);DataSet ds = new DataSet();ad.Fill(ds, "TASKS"); GridView1.DataSource = ds; GridView1.DataBind(); got stuck here, basically I cant work out how to evauate the results of a checkbox, and write back to the database, can anybody help?
View Replies !
Profile, SQLDataSource And GridView
Hello.When I create a user at the ASP.NET database, I need to insert more fields than the defaults, and I do it like this: Dim customProfile As ProfileCommon = ProfileCommon.Create(CreateUserWizard1.UserName, True) customProfile.telephone = (CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("TelephoneText"), TextBox)).Text(telephone example)Those data are inserted at the DB at the aspnet_Profile table, in the fields PropertyNames & PropertyValuesString, but they are saved together (see image above) I want to separate those properties in the GridView as long as each property appears in a column, is it possible? Thank you very much, i'm expecting your answers.
View Replies !
Need Help With Updating A Gridview From Code-behind
Hi, I've got a gridview that displays some (but not all) columns from a sql database table. One of the columns that is NOT displayed is the table's primary key column. I'm putting together this row updating sub based on an article I found on the 'Net. Here's the code I've added for the GridView's edit routine (based on the article):Protected Sub gvPersonnelType_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvPersonnelType.RowEditing gvPersonnelType.EditIndex = e.NewEditIndex gvPersonnelTypeBindData() End Sub Protected Sub gvPersonnelType_RowCancellingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs) gvPersonnelType.EditIndex = -1 gvPersonnelTypeBindData() End Sub Protected Sub gvPersonnelType_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) 'Dim PersonnelTypeID As Integer'This is not displayed in the gridview, but is the primary key in the database Dim LaborForceTypeID As Integer Dim DefaultPayRate, DefaultPieceRate, Rebill As Decimal'These are money datatype in the database Dim DefaultAdminCostPercent, MarkUp As Double 'These are float datatype in the database'Don't know if the following lines properly "capture" the values in the textboxes LaborForceTypeID = Integer.Parse(gvPersonnelType.Rows(e.RowIndex).Cells(0).Text) DefaultPayRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(1).Controls(0), TextBox).Text DefaultPieceRate = CType(gvPersonnelType.Rows(e.RowIndex).Cells(2).Controls(0), TextBox).Text DefaultAdminCostPercent = CType(gvPersonnelType.Rows(e.RowIndex).Cells(3).Controls(0), TextBox).Text Rebill = CType(gvPersonnelType.Rows(e.RowIndex).Cells(4).Controls(0), TextBox).Text MarkUp = CType(gvPersonnelType.Rows(e.RowIndex).Cells(5).Controls(0), TextBox).Text Dim gvSqlConn = New SqlConnection("DATABASECONNECTION") gvSqlConn.open() Dim UpdatePersonnelTypeCmd As New SqlCommand("UPDATE rsrc_PersonnelType SET LaborForceTypeID = @LaborForceTypeID, " & _ "DefaultPayRate = @DefaultPayRate, DefaultPieceRate = @DefaultPieceRate, " & _ "DefaultAdminCostPercent = @DefaultAdminCostPercent, Rebill = @Rebill, Markup = @Markup", gvSqlConn) 'Sql doesn't know what row to update: NEED WHERE STATEMENT!!! UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@LaborForceTypeID", LaborForceTypeID)) UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultPayRate", DefaultPayRate)) UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultPieceRate", DefaultPieceRate)) UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@DefaultAdminCostPercent", DefaultAdminCostPercent)) UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@Rebill", Rebill)) UpdatePersonnelTypeCmd.Parameters.Add(New SqlParameter("@Markup", MarkUp)) UpdatePersonnelTypeCmd.ExecuteNonQuery() gvSqlConn.close() gvPersonnelType.EditIndex = -1 gvPersonnelTypeBindData() End Sub As you can see, I've added some notes in the RowUpdating sub. I don't understand how to use the PersonnelTypeID (the database table's primary key) for the WHERE clause to update the correct row in the database. As for the GridView itself, it's populated from the code-behind as well (as you can see from the call to "gvPersonnelTypeBindData()") and the SELECT statement used to populate the gridview doesn't use the PersonnelTypeID column either. I'd appreciate it if someone could point me in the right direction to get this RowUpdating sub working. Thanks!
View Replies !
Getting A Row Count From A DataSource Vs GridView
There HAS to be an easier way to do this... I have 2 seperate SqlDataSources for 2 distinct filters. How do I get a simple row count for each SqlDataSource? It seems the only way is by using the ObjectDataSource and going through that whole mess (paging, etc.). And unfortunately, you can't simply get the number of rows in the GridView that represents each DataSource if AllowPaging is true for the GridView. This is frustrating. Dave
View Replies !
|