C# Databind question - c#

OK, So Im fairly new to Web apps, been doing Windows app for a while in VB but Im switching to C# for web apps. Ok so I have a textbox and I have a SQLDataSource called SQLDataSource1. How in the world do I bind the source to the textbox so when it loads it will populate it?
Can someone give me some examples?
Ive tried the following,
Label1.Text = SqlDataSource1.SelectParameters.ToString();
But I get something other than the value of the SQLDataSource. I get this: System.Web.UI.WebControls.SqlDataSource
Thanks

I found an answer here on Forum.ASP.Net
Here is what has been said by Samu Zhang (Microsoft Online Community Support) :
It is hard to bind textbox to sqldatasource. We usually bind data controls such as FormView and GridView to sqldatasource and put one TextBox control in their Template . And you can invoke FindControl method of FormView to retrieve the textbox.
See my sample.
protected void Button1_Click(object sender, EventArgs e)
{
TextBox box = FormView1.FindControl("TextBox1") as TextBox;
}
<form id="form1" runat="server">
<div>
<asp:FormView ID="FormView1" runat="server" DataKeyNames="countryid" DataSourceID="SqlDataSource1">
<ItemTemplate>
countryid:
<asp:Label ID="countryidLabel" runat="server" Text='<%# Eval("countryid") %>'></asp:Label><br />
countryname:
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("countryname") %>'></asp:TextBox><br />
</ItemTemplate>
</asp:FormView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
SelectCommand="SELECT * FROM [country]"></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="retrieve value" />
</form>

One way is have your controls in a FormView or DetailsView, then set the DataSourceID of the FormView to the SqlDataSource and in your controls you bind them like so: asp:Label id=... Text='<%# DataBinder.Eval(Container.DataItem, "MyFieldName") %>' />, then on your OnInit of the page you can call MyFormView.DataBind();

Related

Databind() from code behind never reaches the database

My FormView wont DataBind. I get no errors, all the elements are found correctly, when I step through the code everything looks like it works as expecting. The select parameter is set and the FormView is DataBound.
But no data is returned and my database logging shows that the procedure that is meant to be DataBound is never touched.
Update Panel
<asp:updatepanel ID="upnlMixingTankInfo" runat="server">
<ContentTemplate>
<asp:formview id="fvMixingTankInfo" runat="server" datasourceid="SqlDataSourceMixingTankInfo">
<ItemTemplate>
<asp:label runat="server">Vessel Capacity:</asp:label>
<asp:TextBox ID="vesselCapacity" runat="server" class="form-control" Text='<%# Bind("fldVesselCapacity")%>'></asp:TextBox>
</ItemTemplate>
</asp:formview>
</ContentTemplate>
Code Behind:
SourceDropDownList = sender
upnlMixingTankInfo = CType(SourceDropDownList.Parent.FindControl("upnlMixingTankInfo"), UpdatePanel)
fvTankInfo = CTYPE(upnlMixingTankInfo.FindControl("fvMixingTankInfo"), FormView)
If Not IsNothing(SourceDropDownList.SelectedValue) Then
SqlDataSourceMixingTankInfo.SelectParameters.Add("TankName", DropDownListEquipmentList.SelectedValue)
End If
fvTankInfo.Databind()
SQLDATSOURCE:
<asp:SqlDataSource ID="SqlDataSourceMixingTankInfo" runat="server"
ConnectionString="<%$ ConnectionStrings:ZMConnectionString %>"
SelectCommand="EXEC stpWebGetMixTankCapacity #TankName" >
<SelectParameters>
<asp:Parameter Name="TankName" defaultvalue=""/>
</SelectParameters>
Few changes in SqlDataSource and done, I've tested using my own sp, modify it according to your usage.
UpdatePanel & FormView
<asp:UpdatePanel ID="upnlMixingTankInfo" runat="server">
<ContentTemplate>
<asp:FormView ID="fvMixingTankInfo" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:Label ID="Label1" runat="server">Vessel Capacity:</asp:Label>
<asp:TextBox ID="vesselCapacity" runat="server" class="form-control" Text='<%# Bind("Name")%>'></asp:TextBox>
</ItemTemplate>
</asp:FormView>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind, I've tested on load, you can use same code wherever you want.
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters.Add("Id", "10");
}
SqlDataSource with changes:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="GetImages" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
It works perfectly, I've tested before submitting here.

Setting Visiblity of panel inside of formview

I have a FormView that has elements that I want to make available to different users depending on the users access permissions. I have encased each of these inside of a panel and ID'd the panel so that I can call them out from the code behind potentially drilling into the FormView with FindControl but have been unsuccessful so far in getting it worked out.
I've never had much luck with FindControl and was wondering if some of you that are more knowledgeable about it could point me in the right direction here is an example of my code on the aspx and C# code behind that IS NOT working out!
If this were functioning then I would place conditionals to for valid groups under this protected void for this panel to allow these users access to this panel and likewise do the same for other panels where permission was applied.
In this way I would be presenting a custom FormView for each user group based on my ACL. But I just can't get through my head how to drill in with the FindControl properly.
ASPX SAMPLE:
<asp:FormView Width="100%" ID="ChangeFormFV" DefaultMode="Insert" runat="server" DataKeyNames="CAssetID" DataSourceID="UpdateSqlDataSource">
<InsertItemTemplate>
<asp:Panel runat="server" ID="ShortDescPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="LongDescPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="AddNotesPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="ManufacturerPnl" Visible="false">
</asp:Panel>
<asp:LinkButton runat="server" Text="Insert" CommandName="Insert" ID="InsertButton" CausesValidation="True" /> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" ID="InsertCancelButton" CausesValidation="False" />
</ItemTemplate>
C# Codebehind (not working):
protected void ChangeFormFV_Databound(object sender, EventArgs e)
{
if (Session["SessionUType"].ToString() == "ITSec")
{
ChangeFormFV.Row.FindControl("ShortDescPnl.visiblity")="true";
}
}
Appreciate any help that can be offered, been searching for references and reading all I can but just not getting what I need from my results.
The FindControl method returns the actual control. Set the visibility on the control itself. Something like this:
Panel control = ChangeFormFV.Row.FindControl("ShortDescPnl") as Panel;
if (control != null)
control.Visible = true;

asp:ListView SelectedIndexChanging not firing

I've searched in google and bing and seen all posts and even in stackoverflows search but couldn't find the solution.
To be sure about the error I've created a new project it has 1 page which has:
<asp:ListView runat="server" ID="ListView" DataSourceID="SqlDataSource" OnSelectedIndexChanged="ListView_OnSelectedIndexChanged" OnSelectedIndexChanging="ListView_OnSelectedIndexChanging">
<ItemTemplate>
<asp:Label runat="server" ID="Label" Text='<%#Eval("UserName") %>' ></asp:Label><br/>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource runat="server" ID="SqlDataSource" SelectCommand="Select * FROM Users" ConnectionString="<%$ConnectionStrings:DefaultConnection %>"></asp:SqlDataSource>
Output:
Because I've 2 users with name A and B.
Now the problem is that events OnSelectedIndexChanged and OnSelectedIndexChanging are not firing when I click on A or B. How to get the selected index where user is clicking?
Complete Project if anyone wants to look, actually there is no need to: https://app.box.com/s/bhs682q6fqai784kao0zv1tcxgxecr4s
ListView.SelectedIndexChanging Event occurs when an item's Select button is clicked, but before the ListView control handles the select operation.
(A Select button is a button control whose CommandName property is set to "Select".)
Change your code to
<asp:ListView runat="server" ID="ListView" DataSourceID="SqlDataSource" OnSelectedIndexChanged="ListView_OnSelectedIndexChanged" OnSelectedIndexChanging="ListView_OnSelectedIndexChanging" AutoPostBack="true">
<ItemTemplate>
<asp:Label runat="server" ID="Label" Text='<%#Eval("UserName") %>' ></asp:Label>
<asp:LinkButton runat="server" ID="ButtonSelect" CommandName="Select" Text="SelectButton"/><br/>
</ItemTemplate>
</asp:ListView>

Unable to edit Asp.net DropDownList from code behind

I'm working on an ASP.net Web Forms application (not MVC) and I have a DropDownList wrapped by a TemplateField in a DetailsView like this:
<asp:TemplateField>
<ItemTemplate> </ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
<InsertItemTemplate>
<div class="form-group">
<asp:DropDownList ID="myStatus" runat="server" DataSourceID="DBStatus"
DataTextField="DESC" DataValueField="CODE"
Enabled="false" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
</div>
</InsertItemTemplate>
</asp:TemplateField>
as you can see at insertion its not enabled (Enabled="false")
for simplicity I wanted to use the insertion items/fields to achieve a search
so I want to enable my DropDownList for that search
I tried using these from code-behind on DetailsView_PreRender and Page_Load but nothing worked:
DropDownList Status = DetailsView1.FindControl("myStatus") as DropDownList;
Status.Enabled = true;
and i also tried
Status.Attributes.Add("enabled", "enabled");
i also debugged it, and these commands are executed but the DropDownList doesn't want to be enabled.
any thoughts ?
thanks.

Page still refreshes after wrapping the repeater in an update panel

I've two SqlDataSources and two Repeaters, each repeater contains one hyperlink (i also tried using web server button and anchors).
The hyperlinks fetch from the database some values and in the NavigationUrl property I use a string.Format method to create a parameterized url, to pass for the browser, then second repeater is populated according to the value passed in the url which is originally passed by the first repeater's hyperlink
this is my sample code : https://gist.github.com/726213
<asp:ScriptManager id="Scrptmanagr" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="updtpanl" runat="server">
<ContentTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [arrange_by_id], [arrange_by] FROM [arrange_by]">
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:HyperLink ID="HyperLink3" NavigateUrl='<%# string.Format("{0}?SortingType={1}",Request.AppRelativeCurrentExecutionFilePath, Eval("arrange_by_id"))%>' runat="server"><%# Eval("arrange_by") %></asp:HyperLink>
</ItemTemplate>
<SeparatorTemplate>
|
</SeparatorTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [alphabet_id],[arrange_by_id], [value] FROM [alphabet] WHERE ([arrange_by_id] = #arrange_by_id)">
<SelectParameters>
<asp:QueryStringParameter Name="arrange_by_id" QueryStringField="SortingType" Type="Int32" DefaultValue="1" />
</SelectParameters>
</asp:SqlDataSource>
<br /><br />
<asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:HyperLink ID="hyper1" runat="server" NavigateUrl='<%#string.Format("{0}?SortingType={1}&SortBy={2}",Request.AppRelativeCurrentExecutionFilePath, Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>
</ItemTemplate>
<SeparatorTemplate>
|
</SeparatorTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Now! everytime I click any of the hyperlinks it causes a full post back and refreshes the page! Am I missing something ?
Pretty sure an <asp:HyperLink> isn't going to get you a partial update, it renders to HTML as an <a href=".."> tag. You'll need a control that actually causes a postback, an <asp:Button> or <asp:LinkButton>.
Firstly any value you want to pass back don't use query strings, its the same page.
Place the content in hidden field or the buttons CommandArgument
<asp:HiddenField ID="hdnFieldName" Value='<%# Eval("columnName") %>' runat="server" />
then on the comand behind
protected void rptName_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName.Equals("ButtonCommandName"))
{
RepeaterItem objItem = e.Item;
var objFieldValue = (HiddenField)objItem.FindControl("hdnFieldName");
}
}
And remember to set the update panel Mode="conditional' this will cause the updatepanel to only update when one of the following occurs:
1) If a control within the updatepanel causes a postback e.g. asp.net button.
2) If a trigger on the updatepanel occurs (about triggers: http://www.asp.net/web-forms/tutorials/aspnet-ajax/understanding-asp-net-ajax-updatepanel-triggers)
3) Finally if the "Update()" method is called
Otherwise, it won't update and refresh. When its set to always, any postback outside the updatepanel or another updatepanel can trigger the updatepanel to refresh.

Categories

Resources