I have a select query which is return just one row data. I want to show them some different part of a page, not in a repeater, datalist etc...
I do not use asp:label or somtehing like that, then how can I show them from client side like eval or how can I bind Codebehind and call them from client side in html?
edit:
codebehind:
DataTable dt = new DataTable(); ;
dt = myprocedur.User_Load(Int32.Parse(Session["User_ID"].ToString())).Tables[0];
That I want to bind it something or somewhere in page Load.
Then in HTML:
<div><%#Eval("User_Name") %><div>
Use like that where I want, whithout <asp:blabla runat:server />, what is the way of that?
If is it possible, can you give me some exapmle?
edit2:
c#
public static string getData()
{
return "abcd";
}
html
<div><%getData%></div>
I guess we can use st like that, can we adapt it for data from database or similar way for it?
Use Form View ,
<asp:FormView ID="FormView1" runat="server"
DataSourceID="yourDataSource">
<ItemTemplate>
<%# Eval("User_Name") %>
</ItemTemplate>
</asp:FormView>
You can reference here !
In my example , I use DataSourceID="yourDataSource" , if you want to bind fromView's data source from code behind , you can bind likes
FormView1.DataSource = yourDataSoruse ;
FormView1.DataBind();
Edit
DataTable dt = new DataTable(); ;
dt = myprocedur.User_Load(Int32.Parse(Session["User_ID"].ToString())).Tables[0];
FormView1.DataSource = dt ;
FormView1.DataBind();
Related
I have an issue with the following code, the markup is as follows:
<asp:GridView ID="GridView" runat="server"
AutoGenerateEditButton="True"
OnRowDataBound="GridView_RowDataBound"
OnRowEditing="GridView_RowEditing"
OnRowUpdating="GridView_RowUpdating"
CssClass="gridv">
<Columns>
<asp:TemplateField HeaderText="ASN">
<ItemTemplate>
<asp:Label ID="lblASN" runat="server" Text='<% #Eval("ASN")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtASN" runat="server" Text='<%# Bind("ASN")%>' CssClass="form-control"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
...
However when I run this code to get the new changed values from the textboxes that were successfully generated and populated, I only get the initial values not the news that user has entered, the code behind this is:
Protected Sub GridView_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView.RowUpdating
Try
Dim row As GridViewRow = GridView.Rows(e.RowIndex)
Dim ID As Integer = DirectCast(row.FindControl("txtID"), TextBox).Text
Dim sASN As String = DirectCast(row.FindControl("txtASN"), TextBox).Text
Dim sDescription As String = DirectCast(row.FindControl("txtDescription"), TextBox).Text
Dim sManufacturer As String = DirectCast(row.FindControl("ddlmanufacturer"), DropDownList).SelectedValue
GridView.EditIndex = -1
Catch
End Try
ShowEmpDetails()
End Sub
So when I click the update button I use a message box to write the variables above and the values that I get are the same ones that got initially written to the textboxes, not the text that the user has changed?
I have worked out this code from a similar example in which this works with no issues, I honestly can not figure out what I am doing wrong?
As requested Page_Load event is calling this function:
Private Sub ShowEmpDetails()
Dim query As String = "SELECT * from inventory.all_items"
Dim cmd As MySqlCommand
cmd = New MySqlCommand(query)
cmd.Connection = myConn
Dim sda As New MySqlDataAdapter
sda.SelectCommand = cmd
Dim dt As New DataTable
sda.Fill(dt)
GridView.DataSource = dt
GridView.DataBind()
End Sub
Ok... there are so many things wrong with your coding approach that I don't know where to begin. Sorry.
Lets' start again and I'll explain how to properly pass values between the DOM and your code-behind.
Firstly, you need to understand how the DOM populates and builds the HTML for the browser to know what's going on.
I would test your project in Firefox and use the Inspector tool (right-click wep page). That tool is gold and has saved my already bald-head from revealing my skull!! :-)
As you know, the GridView control binds both the "view" and "edit" portions of the control into the same code. I can see you have Eval() for the view portion of the control (or the mode of the control I should say) and you have Bind() for the Edit mode. That is good. I personally hate BoundControls, as you cannot really see what's going on under the hood.
Next, avoid using AutoPostBack like the plaque! It's just ugly.
Get familiar with AjaxControlToolKit (there are others too, but start with the Ajax), and the ASP:UpdatePanel.
So in your case something like this ...
<asp:UpdatePanel ID="upADDMAIN" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView" runat="server"
AutoGenerateEditButton="True"
OnRowDataBound="GridView_RowDataBound"
OnRowEditing="GridView_RowEditing"
OnRowUpdating="GridView_RowUpdating"
CssClass="gridv">
Try and put as much functionality back into the defaults of the GridView control. So go back to your DESIGNER mode in VStudio and add all the functionality you need like EDIT, UPDATE, DELETE, etc in the design mode of the GridView. This will also make sure your SQLDataSource is updated at the same time with the right SQL for the task.
Now why are you using OnRowEditing and OnRowUpdating?
My rule-of-thumb is always to keep things to a minimum and give as much control to ASP.net as possible. This avoids re-inventing the wheel with code-behind stuff that ASP.net can handle straight out of the box.
I generally use OnDataBound(), OnRowDataBound(), and OnRowUpdating() to both read the data and pre-UPDATE the data before the Update() gets called by the controls.
ie:
protected void gvLogins_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvRow = (GridViewRow)e.Row;
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
and
protected void gvLogins_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//apply values to the SQL parameters for UPDATE, etc
GridViewRow gvRow = (GridViewRow)gvLogins.Rows[e.RowIndex];
to do some pre-Update updates outside of the GridView for example.
I never do prerendering or preloading of data in the PageLoad(). That is just re-inventing the wheel, when by default most ASP.net controls already have connectivity and updating built in!
Oh and to get the values of controls inside a GridView... just use FindControl() but in the right place! ie: the DataBound() events etc.
DropDownList ddlAgent = (DropDownList)gvRow.FindControl("ddlAgent");
HiddenField hfAgentID = (HiddenField)gvRow.FindControl("hfAgentID"); //from overall state,as EDIT mode defaults the hfAgentID to 0!
if (ddlAgent != null && hfAgentID != null)
ddlAgent.SelectedValue = hfAgentID.Value;
Sorry I only use C#, not VB.
Good luck.
I am having some trouble figuring out the best way to filter an Entity Framework Query with the results of a DropDownList's Selected Value to fill a ListView Control.
My code is as follows:
Public Function ListViewProducts_GetData() As IQueryable
Dim strVendorName As String = ddlFilterVendor.SelectedValue
Dim myEntities As New InventoryProductsEntities()
Return (From product In myEntities.InventoryProducts
Order By product.ID Ascending
Where product.VendorID = strVendorName
Select product).Take(ddlDisplayRecords.SelectedValue)
End Function
This is pretty rough right now, but I would like to be able to filter this data by vendor, and then page it, but I cannot get the ListView to display the updated queried data. It just continues to display the same data as before, even with a ddlFilterVendor.SelectedValue change.
The drop down list code is as follows:
<asp:DropDownList ID="ddlFilterVendor" runat="server" AutoPostBack="True" DataSourceID="SqlDataSourceVendor" DataTextField="VendorID" DataValueField="VendorID" AppendDataBoundItems="True">
<asp:ListItem Selected="True">All</asp:ListItem>
</asp:DropDownList>
I am stuck at this point.... I was thinking about posting the ddlFilterVendor.SelectedValue to the QueryString and reloading the page, but I would imagine that there should be an easier way to do this. Any help or ideas would be greatly appreciated! Thanks!
The SqlDataSource Code is as follows:
<asp:SqlDataSource ID="SqlDataSourceVendor" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT DISTINCT [VendorID] FROM [InventoryProducts]"></asp:SqlDataSource>
I have found a solution to this problem. In the DropDownList's SelectedIndexChanged event, I called the following method:
ListViewProducts.DataBind()
This re-queried the database with the appropriate Vendor filter, as shown in code snippet:
Public Function ListViewProducts_GetData() As IQueryable
Dim strVendorName As String = ddlFilterVendor.SelectedValue
Dim myEntities As New InventoryProductsEntities()
Return (From product In myEntities.InventoryProducts
Order By product.ID Ascending
Where product.VendorID = strVendorName
Select product).Take(ddlDisplayRecords.SelectedValue)
End Function
Thanks!
I know how to bind a simple datatable to a gridview, but this is a different scenario (I think). I am calling a class library dll which returns a class. I can say its kind of list.
I will call it like,
Dim demo = New ABCDataTable()
demo = demo.GetTheDataTable(MyConnectionString)
GridView1.DataSource = demo
GridView1.DataBind()
Question: How do I bind this to gridview in a markup file? Which datasource control I have to use?
Update:
I used ObjectDataSource and assigned SelectMethod="GetTheDataTable" and used selectparameter to pass connection string.
I am assigning connection string in the code behind ObjectDataSource1.SelectParameters["connectionString"].DefaultValue = MyConnectionString;
but I am getting an error.
i don't know if it will work but try like this -
<asp:GridView id="GridView1" runat="server"
DataSource='<%# (new ABCDataTable()).GetTheDataTable(ConfigurationManager.ConnectionString["nameofyourconnectionstringInwebconfigfile"])) %>' >
</asp:GridView>
You can use a Hidden control as a select parameter for connectionString.
Make sure the default constructor of the class ABCDataTable does not have any parameters.
If it does, then you could create a static method in another class to make the instance and return the result to ObjectDatasource.
I am looking for a line of code that can show how many replies a topic has in my forum. I have a repeater(REPEATER_1) to show other info about each topic, like it's title and text. For example, to get the title, I use:
<%# DataBinder.Eval(Container, "DataItem.title")%>
This works fine, but for counting replies, I need to access another table, and count all replies for this topic. I use the following SelectCommand:
"SELECT COUNT(ID) FROM [replies] WHERE parent='" & <%# DataBinder.Eval(Container, "DataItem.ID")%> & "';"
But how do I execute this SelectCommand from within the Form (and within the repeater area) of the page using <%# XXXX.. %>
I know there are alternatives using code-behind, but I am practicing doing it this way using <%# XXXX.. %>
Also, what is it called when doing script inside a form using "<%# XXXX.. %>" ? It will make it easier for me to search on the web, as google or this website cannot search for "<%#"
I would do this in the ItemDataBound event of the Repeater.
I'm following your current approach, but you should return the reply count with the query that gets the topics. Doing it the way you're doing it, you're calling the database too many times.
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// !! use a parameterized query here to avoid SQL injection
string query = String.Format("SELECT x FROM y WHERE z = {0}", DataBinder.Eval(e.Item.DataItem, "SomeColumn"));
//execute your query to get reply count
int replyCount = ExecuteQuery(query); // !! example
Label lbl = e.Item.FindControl("ReplyCountLabel") as Label;
if (lbl != null)
{
lbl.Text = replyCount.ToString()
}
}
Try
Dim ds As DataSet = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings("connstr").ConnectionString, CommandType.StoredProcedure, "Get_All", New SqlParameter("#userid", Session("userid")))
rptBundles.DataSource = ds.Tables(0)
Catch ex As Exception
showerror(ex, Me)
End Try
That is the code, I want to be able to parse through it and find certain rows that have a certain boolean set to 1 and then edit other variables in that row accordingly, how would I do this, I tried making a For Each row nested in a For Each table but when I tested it the repeater never populates with data...
For Each ds_table As DataTable In ds.Tables
For Each ds_row As DataRow In ds_table.Rows
If ds_row("isScorm") = 1 Then
ds_row("totalLessons") = 100
ds_row("TotalQuestions") = 100
ds_row("lessonscompleted") = 50
ds_row("TotalCorrect") = 50
End If
Next
Next
Only when I remove that code does the repeater populate as expected, but I got no errors!
If you're using a Repeater, or whatever datasource bound control, I would use the ItemDataBound event and set those values to your controls.
If this was your basic HTML
<html>
<asp:Repeater id="repeater" runat="server" OnItemDataBound="repeater_ItemDatabound">
<ItemTemplate>
<span><%# DataBinder.Eval(Container.DataItem, "isScorm") %></span>
<span id="totalLessonsSpan" runat="server"><%# DataBinder.Eval(Container.DataItem, "totalLessons") %></span>
</ItemTemplate>
</asp:Repeater>
</html>
I would have this in the code behind
protected void repeater_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
DataRow row = e.Item.DataItem as DataRow;
if (row == null) { }
else
{
int isScorm = 0;
int.TryParse(Convert.ToString(row["isScorm"]), out isScorm);
if (isScorm > 0)
{
HtmlGenericControl totalLessonsSpan = e.Item.FindControl("totalLessonsSpan") as HtmlGenericControl;
totalLessonsSpan.Text = "100";
}
}
}
You probably don't want to loop through the data and swap it there, then bind when you can do it during the bind.
Alternately, something I hate that DB's do because of my need for data integrity, is change it in your SQL select with case statements.
Does adding rptBundles.DataBind() after setting DataSource fix the problem?
Also, you might want to check out the DataTable.Select method to only select (and then modify) rows where isScorm = 1.