losing the first result of retrieved data when binding it to repeater control - asp.net

I am developing a social network in which i must show a list of friends to the current user.
i am using SqlDataReader to retrieve data from database then bind it by a repeater , the problem is that the repeater always skip the first result so it only shows the n-1 results out of n. anybody can explain to me this behaviour?
my code is:
string cmdstr2 = "SELECT students.fname, students.lname,students.username FROM students INNER JOIN friends ON students.username = friends.tostudent WHERE (friends.fromstudent ='" + cuser + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
SqlDataReader rd = cmd2.ExecuteReader();
if (rd.Read())
{
Repeater1.DataSource = rd;
Repeater1.DataBind();
}
in the design view, i have written this code to include the repeater in the page:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div style="font-size:xx-large;">
الأصدقاء</div>
</HeaderTemplate>
<ItemTemplate>
<div style="font-size:x-large; color:Black; margin-right:0px; margin-top:0px;">
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "student.aspx?user="+DataBinder.Eval(Container.DataItem,"username")%>' >
<%#DataBinder.Eval(Container.DataItem, "fname")%> <%#DataBinder.Eval(Container.DataItem, "lname")%>
</asp:HyperLink>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>

Your rd.Read() in your if statement is advancing it 1 record
Try using:
if (rd.HasRows)

Related

Bind Listview Inside Listview for sub menus(child menus)

I am little confused for creating website menu & sub menus which is completely dynamic & made from database. For Menus I used Listview Control which is fine now all menus have submenus(child menu) as well which is based on menus. Now I don't understand how to do it. I guess using nested ListView would be good for this but I need an hint how to bind nested listview?
This is my main Listview
<asp:ListView ID="mainMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Private Sub bigMenu()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM mainMenu WHERE status = 'active' order by CAST(position as SIGNED INTEGER) asc"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
mainMenu.DataSource = dt
mainMenu.DataBind()
End Using
End Using
End Using
End Sub
You need to use ListView ItemDataBound to bind your nested listview. ItemDatBound will get rows value for you. See the below code I done for you
<asp:ListView ID="mainMenu" runat="server" DataKeyNames="enter column name you want">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Protected Sub onItemDataBound(sender As Object, e As ListViewItemEventArgs)
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim itm As ListViewDataItem = CType(e.Item, ListViewDataItem)
Dim name As String = mainMenu.DataKeys(itm.DataItemIndex)("enter your datakeyname")
Dim childMenu As ListView = TryCast(e.Item.FindControl("childMenu"), ListView)
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM tablename WHERE column = '" + name + "'"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childMenu.DataSource = dt
childMenu.DataBind()
End Using
End Using
End Using
End If
End Sub

Linking SqlDataSource to label for a single item in ASP.NET

I have a asp:SqlDataSource that returns a single row. How do I return that value into a label. I got it working in a asp:DataList but its overkill since its a single record.
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionString %>"
SelectCommand="SELECT STATEMENT">
</asp:SqlDataSource>
<asp:DataList ID="DataList5" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label ID="label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
</ItemTemplate>
</asp:DataList>
Here is one way to do it in C#:
DataView oDV = (System.Data.DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
Label1.Text = string.Join("|", oDV.Table.Rows[0].ItemArray.Select(p => p.ToString()).ToArray());
I guess my project is using an actual method instead of a property like I first suggested.
You could use a text SqlCommand(String, SqlConnection), passing the select statement and a SqlConnection(String) to your database.
public string GetSelectStatement()
{
SqlConnection conn = new SqlConnection(ConnectionString);
string selectStatement = "SELECT TOP 1 ID FROM Customer";
SqlCommand comm = new SqlCommand(selectStatement, conn);
comm.CommandType = System.Data.CommandType.Text;
SqlDataReader reader = comm.ExecuteReader();
// My code has a while, but you shouldn't need it with only one record
reader.Read();
string ID = (string)reader["ID"];
return ID;
}
Then in your page (aspx) or control (ascx) you can use that method to bind the label text
<asp:Label ID="label1" runat="server" Text='<%# GetSelectStatement() #>'></asp:Label>

Dropdown list to populate checkboxes

My asp.net application currently uses a Telerik RadGrid to show product data. At the top of the page, I have a dropdown list that will include 4 different categories. Based on the user's selection of category, the checkboxes in the grid will either become checked or not checked. The website's 1500 products will always show in the grid, it's the checkboxes that will be changing.
Ex: Product 1 is in Category A, therefore if a user clicks on Category B in the dropdown, the checkbox next to Product 1 will be unchecked. The only way that will be checked is if the user changes the dropdown to view the products currently in Category A.
I am having trouble trying to figure out how to approach this. For one, the line if (ProductInMarket.Checked = true) throws an error sayingThe name ProductInMarket' does not exist in the current context.` The second problem I have is that I can't figure out how to finish the UpdateMarket method. That's what happens when you take a lunch in the middle of coding. :/
This is what I have so far and I would really appreciate some help here.
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
I would recommend using batch updating via Performing Batch Operations Using DataAdapters.
Note: The UpdateBatchSize property is the key here, because it tells ADO.NET how many items to send in each batch. Setting it to zero will force the batch to be as large as possible, setting it to 1 will basically make it ignore batching, because it will send one at a time. You will need to play with this value to get the optimal value, taking into account performance and memory-usage (larger batches will use up more memory until it is cleaned up).
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
try this
jsfiddle

How to Redirect to new asp page while clicking on the data row of the data grid view in asp.net

My data grid view in asp.net displays only selected id from sql server database as a single row.
Now I need to display a particular page when I click on the particular id (data row) and also I want to display all the details in a new page belongs to the selected id (on click on the id).
I have tried this code:
protected void btnserch_Click(object sender, EventArgs e)
{
SqlConnection objsqlconnection = new SqlConnection(CONNECTIONSTRING);
string query = "Select id from registration";
SqlCommand objsqlcommand = new SqlCommand(query, objsqlconnection);
objsqlconnection.Open();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds=new DataSet();
objsqlcommand.CommandText = query;
objsqlcommand.Connection = objsqlconnection;
da = new SqlDataAdapter(objsqlcommand);
da.Fill(ds);
objsqlcommand.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
objsqlconnection.Close();
}
This code returns a grid by selecting only id column from registration table. Now when I click on the data row of the id column, I need an another page which should display all the details belonging to that id.
like #MelanciaUK said "OnItemDataBound" is your friend.
For checking ID even on postback, select it in "SelectedIndexChanging"
hope it helps.
Easiest way to redirect to new page:
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="ID">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Name">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Edit">
<ItemTemplate>
<a href='Newpage.aspx?ID=<%#Eval("ID")%>'>Edit</a>
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
You can redirect from one page another page in two ways
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="Action">
<ItemTemplate>
<a href='mypage.aspx?ID=<%#Eval("RowID")%>'>Edit</a>
Edit
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
<script type="text/javascript">
function Redirect(id) {
window.location = 'mypage.aspx?ID=' + id;
}
</script>

xml format in asp.net

I have a table in sqlserver, in that table i have a column having xml file. i am displaying that table in gridview. when we click on button i want to display that particular xml column file column in a xml format. tank you.
i take one dtalist and writ code like this.
<asp:DataList ID="dtlstOne" runat ="server" >
<ItemTemplate >
<asp:TextBox ID="txtname" runat ="server" Text ='<%# XPath("/EXTPOSTTRANSACTION/STLTRANSACTIONINFO/TRANSACTIONTYPE")%>' ></asp:TextBox>
<asp:TextBox ID="TextBox1" runat ="server" Text ='<%# XPath("/EXTPOSTTRANSACTION/STLTRANSACTIONINFO/USERID")%>' ></asp:TextBox>
</ItemTemplate>
</asp:DataList>
it is giving error
An exception of type 'System.ArgumentException' occurred in System.Web.dll but was not handled in user code
Additional information: XPath DataBinding: 'System.Data.DataRowView' must implement IXPathNavigable.
please can u help me
string sqry = "select NewLoanRequestXML from tbl_newloanxml where newloanid=" + Request.QueryString["id"].ToString();
da = new SqlDataAdapter(sqry, con);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
dtlstOne.DataSource = ds;
dtlstOne.DataBind();
}

Resources