ASP.NET GridView control with MySQL - UpdateQuery with spaces in parameters - asp.net

I have a project I'm making with Visual Studio 2010 and ASP.NET Web Forms. In it, I have a GridView control that I bound to a MySQL table. It displays my table in the control without a problem, but after I enabled editing on the control I found I had problems updating fields in the table when the field has a space in it.
For example, I have the following table defined:
CREATE TABLE `test_table` (
`oid` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_column` varchar(20) NOT NULL,
`second_column` varchar(20) NOT NULL,
`third column` varchar(20) NOT NULL,
PRIMARY KEY (`oid`)
)
Note one of the fields has a space in the name. This is where I have problems. In my page, I have the following code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="oid" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="oid" HeaderText="oid" ReadOnly="True"
SortExpression="oid" />
<asp:BoundField DataField="first_column" HeaderText="first_column"
SortExpression="first_column" />
<asp:BoundField DataField="second_column" HeaderText="second_column"
SortExpression="second_column" />
<asp:BoundField DataField="third column" HeaderText="third column"
SortExpression="third column" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testcon %>"
ProviderName="<%$ ConnectionStrings:testcon.ProviderName %>"
SelectCommand="select * from test_table" UpdateCommand="update `test_table` set
`first_column` = #first_column,
`second_column` = #second_column
where
`oid` = #oid"></asp:SqlDataSource>
By way of the UpdateCommand, I am able to update first_column and second_column on this table just fine. Now I want it to update third column the same way, but it doesn't work. If I change the query to this:
update `test_table` set
`first_column` = #first_column,
`second_column` = #second_column,
`third column` = #third column
where
`oid` = #oid
It will give me this error when the query runs:
Parameter '#third' must be defined.
I've also tried #third\ column, #{third column}, #[third column], {#third column} - obviously none of these work. Therefore my question is: what do I put for my update query to be able to update my MySQL field that has a space in it?

You should be able to use any parameter name through the update parameters
http://www.asp.net/web-forms/tutorials/data-access/accessing-the-database-directly-from-an-aspnet-page/inserting-updating-and-deleting-data-with-the-sqldatasource-vb
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testcon %>"
ProviderName="<%$ ConnectionStrings:testcon.ProviderName %>"
SelectCommand="select * from test_table" UpdateCommand="update `test_table` set
`first_column` = #first_column,
`second_column` = #second_column
where `oid` = #oid">
<UpdateParameters>
<asp:Parameter Name="first_column" Type="String" />
<asp:Parameter Name="second_column" Type="String" />
<asp:Parameter Name="third_column" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>

A solution to this situation is to provide an alias name to the column in the Select statement that populates the Gridview. For example:
SELECT ..., [third column] AS third_column, ...
FROM ...
And then you can use #third_column as the parameter name. Since I anticipate that you may want to show the column header with a space instead of an underscore, you can set the HeaderText property of this field to what you want.
With this approach, the Update command of the GridView will easily map to the corresponding parameter (since they have the same name) and you don't have to change the definitions in your database. I also recommend using SQLServer Profiler to see the actual T-SQL code that is executed in the server.
Good luck!

Related

GridView hyperlink for Date field is not displaying using vb.net

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="637px" CssClass="auto-style1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="TimeStamp" DataNavigateUrlFormatString="Logs.aspx?TimeStamp={0}" DataTextField="TimeStamp" HeaderText="TIME STAMP"></asp:HyperLinkField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SoneilCloudRemConnectionString %>"
SelectCommand="SELECT [TimeStamp] FROM [SensorLogData] WHERE ([deviceId] = #deviceId)">
<SelectParameters>
<asp:Parameter DefaultValue="121313131" Name="deviceId" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The above is the code snippet used for displaying date with hyperlink. For me it displays just the date instead of it to be hyperlink. In my SQL the datatype for this date is in "datetime" format.
I tried using other field to display in hyperlink, it's working. Finding issue only for datetime.
The Gridview won't build a URL containing : (which is in the time portion of Timestamp). This results in an <a> tag being created with no href.
If you can live without the time, you can change the DataNavigateUrlFormatString to only use the date portion:
DataNavigateUrlFormatString="Logs.aspx?TimeStamp={0:d}"
Another option is described here. It would involve formatting Timestamp to a specific format & then parsing the querystring Timestamp using `DateTime.ParseExact().
DataNavigateUrlFormatString="Logs.aspx?TimeStamp={0:yyyy-MM-dd hh-mm-ss}"
Then on Logs.aspx:
DateTime.ParseExact(Request.QueryString("Timestamp").ToString(), "yyyy-MM-dd hh-mm-ss", System.Globalization.CultureInfo.CurrentCulture)

Gridview's UPDATE does not like the space in my parameter

Unfortunately, the database I'm dealing with has a space in the column name. I have a DropDownList in a GridView and I'm trying to update the column with whatever the user selects in the DropDownList. Here's how I have the DropDownList:
<asp:TemplateField HeaderText="Phase (edit)" SortExpression="EditedPhase">
<EditItemTemplate>
<asp:DropDownList ID="PhaseDropDownList" runat="server" DataSourceID="PhaseDropDown" DataTextField="Current Project Phase" DataValueField="Current Project Phase" SelectedValue='<%# Bind("Phase") %>'>
</asp:DropDownList>
</EditItemTemplate>
<asp:TemplateField>
Here's the data source:
<asp:SqlDataSource ID="PhaseDropDown" runat="server" ConnectionString="<%$ ConnectionStrings:ODSConnectionString %>" SelectCommand="select distinct [Current Project Phase] from [Phase_Table]">
</asp:SqlDataSource>
Here's how I have my update command and the parameter:
UpdateCommand="UPDATE [Pipeline] SET EditedPhase = #[Current Project Phase]"
<UpdateParameters>
<asp:Parameter Name="[Current Project Phase]" Type="String"/>
</UpdateParameters>
After doing a little bit of research, I discovered that you can not have spaces in the parameter, but most of the solutions used the code behind. I have no code behind because introducing code behind could potentially break it (needing to deal with page loads and such). How do I fix my current issue?
If there's a typo, sorry.
Yes, do not use spaces in your parameter name; the value passed to the parameter can have spaces though, so I'm not sure if that is a point of confusion. For instance, update your SQL query like:
UpdateCommand="UPDATE [Pipeline] SET EditedPhase = #CurrentProjectPhase">
<UpdateParameters>
<asp:Parameter Name="CurrentProjectPhase" Type="String" DefaultValue="Current Project Phase"/>
</UpdateParameters>
Here the value (the DefaultValue is a default to supply to the update when no value is provided) can have spaces just fine. But the name cannot. You can set the DefaultValue of the parameter in code or use a more capable parameter (like session, control parameters) to grab values from something...

ASP.NET GridView & SqlDataSource FilterExpression - Column name with hash / pound symbol

I am working with a brilliantly designed table, where the primary key column contains a #: OTTXN#
I need to be able to select and display these values in the GridView which is populated from my SqlDataSource, which is working fine.
When i add FilterExpression=" = '{0}'" then the code craps out on me, because the column name has a hash tag / pound symbol in it.
I'm able to alter the select statement to use an alias without the pound symbol, but SQL where clauses dont allow you to use a column alias.
Any way i can get this to work?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="dsIseries">
<Columns>
<asp:BoundField DataField="OTTXN#" HeaderText="OTTXN"
SortExpression="OTTXN#" />
<asp:BoundField DataField="OTWODT" HeaderText="OTWODT"
SortExpression="OTWODT" />
<asp:BoundField DataField="OTBAD1" HeaderText="OTBAD1"
SortExpression="OTBAD1" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsIseries" runat="server"
ConnectionString="<%$ ConnectionStrings:VM520ConnectionString %>"
ProviderName="<%$ ConnectionStrings:VM520ConnectionString.ProviderName %>"
SelectCommand='SELECT ottxn#, otwodt, otbad1
FROM kivalib.ortxnpf
fetch first 100 rows only'
FilterExpression=" = '{0}'">
<FilterParameters>
<asp:ControlParameter ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
EDIT
Without making changes to the database... is there a way i could query the columns from the code-behind and pass the results back to the SqlDataSource or GridView with the values & altered column name?
I would create a VIEW in the DB that includes all the relevant columns with better names and then query from that view.

change text on a hyperlink in a datalist

I'm trying to bind a column from a SQL code that i have written to all hyperlinks in a datalist. This should be really simple but I'm getting the error
DataBinding: 'System.Data.Common.DataRecordInternal' does not contain
a property with the name 'NumberOfComments'.
Well I'm pretty sure the column exist but in this case it's created by a function maybe that has something to do with it. When I run the SQL code i get the values I should.
The hyperlink
<asp:HyperLink ID="lnkComment" runat="server"
NavigateUrl='<%# Eval("ID", "~/Default.aspx?ID={0}") %>'
Text='<%# Eval("NumberOfComments") %>'></asp:HyperLink>
The SQLDataSource
<asp:SqlDataSource ID="sdsNews" runat="server"
ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString %>" SelectCommand="SELECT News.ID, News.Topic, News.Text, News.PostTime, aspnet_Users.UserName, "NumberOfComments" = dbo.fnNumberOfCommentOnNews(News.ID)
FROM News INNER JOIN
aspnet_Users ON News.UserId = aspnet_Users.UserId
WHERE (News.ID = ISNULL(#ID, News.ID))
ORDER BY News.PostTime DESC ">
<SelectParameters>
<asp:QueryStringParameter DbType="Guid" Name="ID" QueryStringField="ID" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Why do you have """ surrounding NumberOfComments FieldName?
Try pasting the select command into SSMS (SQL Server Mgmt studio) and you should most definitely get an incorrect syntax error. If you drop those quot html code you will still be able to reference and bind to that column.

Accessing query string variable in the sql query in aspx page

I am quite new to asp.net,I am building an application where I need to show the in the grid view,Now the query I am generating for fetching the data from database containing one parameter which comes from the query string.I am using this code
<asp:SqlDataSource runat="server" ID="MySQLData"
ConnectionString="server=localhost;port=3309; User Id=xxxxx;password=xxxxx;database=xxxxx"
ProviderName="MySql.Data.MySqlClient"
SelectCommand="SELECT contenthead.lastmodifieddate,contenthead.heading,lk_technology.technology FROM contenthead JOIN lk_technology WHERE contenthead.techID=lk_technology.techID AND contenthead.authorid='<%=Request.QueryString["uid"]%>'" />
Now when I am using <%..%> tag I am getting parser error that says: Server tags cannot contain <% ... %> constructs.
Now I want to use this variable from query string.Please tell me how I can access this variable in this context.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..." ProviderName="System.Data.SqlClient" SelectCommand="SELECT [UserId], [LastUpdatedDate] FROM [vw_aspnet_Profiles] WHERE ([UserId] = #UserId)">
<SelectParameters>
<asp:QueryString ParameterDefaultValue="0" Name="UserId" QueryStringField="Id" Type="Object"/>
</SelectParameters>
</asp:SqlDataSource>
You have to add a parameter to your SqlDataSource

Resources