How to pass asp.net value to javascript function? - c#

I have this code
<asp:GridView ID="gvCentersList" runat="server" AutoGenerateColumns="False"
DataKeyNames="CenterID" DataSourceID="SqlDataSource1" CssClass="gv-classic">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox ID="GridCheckBox" runat="server" onclick="javascript:func1150(this,<%#response.write(CenterID)%>);" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CenterID" HeaderText="CenterID" SortExpression="CenterID" />
<asp:BoundField DataField="CenterName" HeaderText="CenterName" SortExpression="CenterName" />
</Columns></asp:GridView><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT ROW_NUMBER() OVER (ORDER BY CityName ASC) AS ROWID, * FROM [CentersList]"></asp:SqlDataSource>
my question in this line
onclick="javascript:func1150(this,<%=CenterID%>);"
how can I pass the CenterID to the func1150 ?

You may try like this:
<asp:CheckBox
ID="GridCheckBox"
runat="server"
onclick='<%# string.Format("javascript:func1150(this, \"{0}\")", Eval("CenterID")) %>'
/>
But do you really need a server side checkbox here? If not this could be more readable:
<input
type="checkbox"
onclick="javascript:func1150(this, '<%# Eval("CenterID") %>');"
/>

From my understanding of your question,
onclick=javascript:func1150(this,'<%# Eval("CenterID")%>');
A better way would be adding the onclick attribute from code behind.

Related

ASP.NET SqlDataSource filter behaviour

I have a GridView object fed trough a SqlDataSource. In the same form I have also a number of TextBoxes used to build a filtering expression for the datasource. The filtering is started by pressing a Button.
<asp:GridView
DataSourceID="sdsTable1"
OnSorting="gvTable1_Sorting"
OnPageIndexChanging="gvTable1_PageIndexChanging"
runat="server"
CssClass="list_table"
ID="_gvTable1"
CellPadding="0" CellSpacing="0"
AutoGenerateColumns="false"
EmptyDataText="No data."
ShowHeader="true" ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
OnRowDataBound="gvTable1_RowDataBound" >
<HeaderStyle CssClass="header" />
<FooterStyle CssClass="footer" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Next page"
PreviousPageText="Prev page"
FirstPageText="First page"
LastPageText="Last page" />
<RowStyle CssClass="odd" />
<AlternatingRowStyle CssClass="even" />
<PagerStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="date">
<ItemTemplate>
<%#Eval("date","{0:dd/MM/yyyy HH:mm:ss}")%>
</ItemTemplate>
<FooterTemplate>
TOTALE:
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price","{0:F2} €") %>'>></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTable1" runat="server"
ConnectionString="<%$ ConnectionStrings:_db %>"
ProviderName="<%$ ConnectionStrings:_db.ProviderName %>"
DataSourceMode="DataSet"
SelectCommand=" SELECT id, id_user, price, description FROM view1 WHERE id_user = #id_user;">
<SelectParameters>
<asp:SessionParameter Type="Int32" Name="id_user" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
In codebehind (in the event hanlder associated with the Button mentioned above) I build up the filter expression chaining TextBoxes values, with this code:
if (!string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()))
{
_sFilter += "(description LIKE '%" + _txtFilter0.Text.Trim() + "%')";
}
if (!string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()))
{
if (!string.IsNullOrWhiteSpace(_sFilter))
_sFilter += " AND";
_sFilter += "(description LIKE '%" + _txtFilter1.Text.Trim() + "%')";
}
sdsTable1.FilterExpression = _sFilter;
Everything works until I clear the fields that leads to an empty filter, im such circumstances I expected to retrieve all the records but for some reason, in this case, the last recordset is kept and shown apparently without a reason.
I tried also to disable the SQLDataSource caching feature without luck:
EnableCaching="false"
I tried also to issue a Select command, again without luck:
sdsTable1.Select(DataSourceSelectArguments.Empty);
Where I'm wrong?
Your _sFilter property will be persisted across postbacks, so as you're only updating it when your filter text boxes are not empty it will remain at the last set value when you clear them. Putting a breakpoint in your code at the line _sdsTable1.FilterExpression = _sFilter; should confirm this.
To solve the issue, either clear the _sFilter property before rebuilding it in your event handler, or write an additional check:
if (string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()) & string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()) )
{
_sFilter = null;
}

What causes 'Both DataSource and DataSourceID are defined on 'DataListCity'. Remove one definition' error?

I am getting this error
"Both DataSource and DataSourceID are defined on 'DataListCity'. Remove one definition."
This is the code from my Masterpage that is causing the error
<asp:DataList ID="DataListCity" runat="server" Width="100%"
onitemcommand="DataListCity_ItemCommand" CellPadding="4"
ForeColor="#333333" DataSourceID="SqlDataSource1">
<ItemTemplate>
CityId:
<asp:Label ID="CityIdLabel" runat="server" Text='<%# Eval("CityId") %/>
<br />
CityName:
<asp:Label ID="CityNameLabel" runat="server" Text='<%# Eval("CityName")%>' />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource
ConnectionString="<%$ ConnectionStrings:HotelConnString %>"
ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [CityId], [CityName], [Description] FROM [Categories]">
</asp:SqlDataSource>
Remove your binding code from cs if you have written in code behind because you can bind only by code behind or from design not both at same time
Remove these lines from code behind
DataListCity.DataSource=somesource;
DataListCity.DataBind();

How do I send multiple users message using a gridview with templates

How do I send mltiple users message using a griview which should be connected to two tables namely login(from where usernames will be retrieved and shown) and then the second table message (where a message is to be stored for particular usernames). I have connected it to login but I am not able to insert values into message table. Message table has msg_id , username and message columns.
Here is the design:
.aspx
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataSourceID="SqlDataSource1"
onrowcommand="GridView2_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="username"
SortExpression="username" />
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AutomobileConnectionString14 %>"
SelectCommand="SELECT * FROM [login] WHERE ([utype] LIKE '%' + #utype + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="U" Name="utype" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
aspx.cs code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("cc"))
{
TextBox txt1 = (TextBox)GridView2.FooterRow.FindControl("TextBox1");
foreach(GridView gr in GridView2.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("CheckBox1");
if (chk.Checked)
{
Object ob = GridView2.DataKeys[gr.RowIndex].Value;
}
now I am stuck her how can I insert values into other table message when it is already connected to Login table. Help me what I want to accomplish here is send message to checked users.
Try below :
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="userId"
OnRowCommand="GridView2_RowCommand" OnRowEditing="GridView2_RowEditing" OnRowUpdated="GridView2_RowUpdated" OnRowUpdating="GridView2_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label Text='<%# Eval("username") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label Text='<%# Eval("messgae") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
On RowDataBound event to set the edit textbox for message by find control.
And refer to code for inline editing on check box click.
http://www.c-sharpcorner.com/UploadFile/9f0ae2/gridview-edit-delete-and-update-in-Asp-Net/
http://www.codeproject.com/Articles/23471/Editable-GridView-in-ASP-NET

Show images in datalist ASP.NET

I want to show Images in my datalist. Image URLs are stored in my database. For some reason urls can't be retrived from my database.
Anyone knows what Am I missing? Here is my code.
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatColumns="3" Width="100%">
<ItemTemplate>
<asp:Image runat="server" ImageUrl="http://mywebsite.com/folder/{0}" Width="100%" />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [url] FROM [MyDatabase]"></asp:SqlDataSource>
There is problem in binding image to image control. Try this.
<asp:Image runat="server" ImageUrl='<%# "http://mywebsite.com/folder/" + Eval("url") %>' Width="100%" />
Or
<asp:Image runat="server" ImageUrl='<%# "~/folder/" + Eval("url") %>' Width="100%" />

Using filters with gridview and stored procedures in ASP.NET and C#

I have a gridview that's populated by a stored procedure. On this dataset, the user should be able to filter it by selecting the LabID and/or SiteName from 2 dropdownlists. What is the best way to accomplish this?
<asp:DropDownList ID="ddlLabIDs" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="LabID"
DataValueField="LabID" AppendDataBoundItems="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="exec usp_LabIDs_Select;"></asp:SqlDataSource>
<asp:DropDownList ID="ddlSiteNames" runat="server"
DataSourceID="SqlDataSource3" DataTextField="SiteName"
DataValueField="SiteName" AppendDataBoundItems="True"
AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="exec usp_SiteNames_Select;"></asp:SqlDataSource>
<asp:GridView ID="AllDataFlat" runat="server" AllowPaging="True" PageSize="20"
AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="LabID" HeaderText="LabID" SortExpression="LabID" />
<asp:BoundField DataField="SiteName" HeaderText="SiteName"
SortExpression="SiteName" />
<asp:BoundField DataField="StartDateTime" HeaderText="StartDateTime"
SortExpression="StartDateTime" />
<asp:BoundField DataField="FilterNumber" HeaderText="FilterNumber"
SortExpression="FilterNumber" />
<asp:BoundField DataField="AmtWaterFiltered" HeaderText="AmtWaterFiltered"
ReadOnly="True" SortExpression="AmtWaterFiltered" />
<asp:BoundField DataField="WaterTemp" HeaderText="WaterTemp" ReadOnly="True"
SortExpression="WaterTemp" />
<asp:BoundField DataField="pH" HeaderText="pH" SortExpression="pH" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="exec usp_AllDataFlat_Select;">
</asp:SqlDataSource>
Thank you.
you can try like this.....
NOTE : this is just example on how to filter the grid view with the selected values on two drop down lists...
<%# page autoeventwireup="true" codefile="FilterWithMultipleDropDownLists.aspx.cs"
inherits="GridView_FilterWithMultipleDropDownLists" language="C#" masterpagefile="~/MasterPages/Default.master"
title="GridView: Filter With Multiple DropDownLists" %>
<asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1">
<div>
Select Supplier:
<asp:dropdownlist id="ddlSuppliers" runat="server" appenddatabounditems="True" autopostback="True"
datasourceid="sdsSuppliers" datatextfield="CompanyName" datavaluefield="SupplierID">
<asp:listitem text="All Suppliers" value="-1">
</asp:listitem>
</asp:dropdownlist>
<asp:sqldatasource id="sdsSuppliers" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
selectcommand="SELECT [SupplierID], [CompanyName] FROM [Suppliers] ORDER BY [CompanyName]">
</asp:sqldatasource>
</div>
<div style="margin-top: 12px;">
Select Category:
<asp:dropdownlist id="ddlCategories" runat="server" appenddatabounditems="True" autopostback="True"
datasourceid="sdsCategories" datatextfield="CategoryName" datavaluefield="CategoryID">
<asp:listitem text="All Categories" value="-1">
</asp:listitem>
</asp:dropdownlist>
<asp:sqldatasource id="sdsCategories" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
selectcommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER By [CategoryName]">
</asp:sqldatasource>
</div>
<asp:gridview id="gvProducts" runat="server" autogeneratecolumns="False" datakeynames="ProductID"
datasourceid="sdsProducts" style="margin-top: 24px;">
<columns>
<asp:boundfield datafield="ProductID" headertext="ProductID" insertvisible="False"
readonly="True" sortexpression="ProductID" />
<asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName" />
<asp:boundfield datafield="CompanyName" headertext="Supplier" sortexpression="CompanyName" />
<asp:boundfield datafield="CategoryName" headertext="Category" sortexpression="CategoryName" />
</columns>
</asp:gridview>
<asp:sqldatasource id="sdsProducts" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
selectcommand="SELECT [P].[ProductID], [P].[ProductName], [P].[SupplierID], [P].[CategoryID], [S].[CompanyName], [C].[CategoryName] FROM [Products] AS [P] INNER JOIN [Suppliers] AS [S] ON [S].[SupplierID] = [P].[SupplierID] INNER JOIN [Categories] AS [C] ON [C].[CategoryID] = [P].[CategoryID] WHERE ([P].[SupplierID] = CASE WHEN #SupplierID = -1 THEN [P].[SupplierID] ELSE #SupplierID END AND [P].[CategoryID] = CASE WHEN #CategoryID = -1 THEN [P].[CategoryID] ELSE #CategoryID END) ORDER BY [P].[ProductName]">
<selectparameters>
<asp:controlparameter controlid="ddlSuppliers" name="SupplierID" propertyname="SelectedValue" type="Int32" />
<asp:controlparameter controlid="ddlCategories" name="CategoryID" propertyname="SelectedValue" type="Int32" />
</selectparameters>
</asp:sqldatasource>
</asp:content>
I hope it will helps you..
The most efficient way to do this would be to pass the values selected in the drop down controls to the stored procedure usp_AllDataFlat_Select. In this stored procedure you should be able to select only the rows that satisfy the filter values.
If you do not have access to the stored procedures (can't modify them) than in my oppinion the best way to achieve this is to wrap your call to the stored procedure in an object that retrieves all the rows from the data base and filters them in memory (not very efficient). Then you can use an OnjectDataSource instead of the SqlDataSource to populate the gridview. This ObjectDataSoruce could call the methods of the object that wraps your stored procedures.
You can find an example here. The example uses queries instead of stored procedures but replacing the queries with calls to stored procedures should be trivial.
Best of luck,

Categories