how to formate string of tree view - asp.net

i have one tree view. i want to formate appended string like grid view:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%#Eval("Inquiry_subject").ToString().Length > 10 ? Eval("Inquiry_subject").ToString().Substring(0,10)+"..." :Eval("Inquiry_subject") %>'
ToolTip='<%# Bind("Inquiry_subject") %>'></asp:Label>
</ItemTemplate>
how ever i want this this to do with my tree view:
<asp:TreeView ID="TV_Question_Summary" runat="server" ImageSet="Simple" ShowLines="True" OnTreeNodeDataBound="TV_Question_Summary_DataBound" SkipLinkText="">
<DataBindings>
<asp:TreeNodeBinding DataMember="Root" FormatString=" {0}" TextField="" ValueField=""/>
<asp:TreeNodeBinding DataMember="ParentNode" FormatString=" {0}" TextField="Inquiry_id" ValueField="Inquiry_id"/><asp:TreeNodeBinding DataMember="Node" FormatString=" {0}" TextField="body" ValueField="Inquiry_id" ToolTip="body"/>
</DataBindings>
</asp:TreeView>
i want to string presentation like ... if Node filed body string gets overflow of no of 15 chars...
for binding up text i use this code:
void fill_Tree()
{
using (SqlConnection conn = Util.GetConnection())
{
conn.Open();
SqlCommand SqlCmd = new SqlCommand("Select * from tbl_Inquiry_History Where (IsDisplay='True')", conn);
SqlDataReader Sdr = SqlCmd.ExecuteReader();
SqlCmd.Dispose();
string[,] ParentNode = new string[100, 2];
int count = 0;
while (Sdr.Read())
{
ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
}
Sdr.Close();
for (int loop = 0; loop < count; loop++)
{
TreeNode root = new TreeNode();
root.Text = ParentNode[loop, 1];
root.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ ParentNode[loop, 1];
SqlCommand Module_SqlCmd = new SqlCommand("Select * from tbl_Question where (Inquiry_id = #parent_id AND IsCount='False')", conn);
Module_SqlCmd.Parameters.AddWithValue("#parent_id", ParentNode[loop, 0]);
SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
while (Module_Sdr.Read())
{
TreeNode child = new TreeNode();
child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("body")).ToString();
child.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ParentNode[loop, 0];
root.ChildNodes.Add(child);
}
Module_Sdr.Close();
TV_Question_Summary.Nodes.Add(root);
}
TV_Question_Summary.CollapseAll();
}
}
please help me...

Try using a code-behind method instead of embedded code blocks, like this:
protected string DisplayInquirySubject(string inquirySubject)
{
return inquirySubject.Length > 10
? inquirySubject.Substring(0, 10)
: inquirySubject;
}
Now in your markup, you can call the method like this:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%# DisplayInquirySubject(Eval("Inquiry_subject").ToString()) %>'
ToolTip='<%# Bind("Inquiry_subject") %>'>
</asp:Label>
</ItemTemplate>
This has two benefits, it simplifies your markup logic and it allows you to leverage the power of the Visual Studio code editor (i.e. Intellisense and debugging).

Related

Dropdown List selected value display only one using Asp.net

i have load the DropDownList successfully. all student numbers i have loaded when i select the student no relavent student name should diplay on the below textbox. but now if select any number only one student name is shown John name only. if i select diffent student numbers. i don't know why.
DropDownList Load code
string cmdstr = "select id from records";
SqlCommand cmd = new SqlCommand(cmdstr, con);
con.Open();
read = cmd.ExecuteReader();
DropDownList1.Items.Clear();
while (read.Read())
{
DropDownList1.Items.Add(read["id"].ToString());
}
con.Close();
Selected data
<asp:DropDownList ID="DropDownList1" ViewStateMode="Enabled" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
if (Page.IsPostBack == true)
{
string cmdstr = "select firstname from records where id = " +
DropDownList1.SelectedValue;
SqlCommand cmd = new SqlCommand(cmdstr, con);
con.Open();
read = cmd.ExecuteReader();
while (read.Read())
{
name.Text = read["firstname"].ToString();
}
con.Close();
}
I have a example: evt. this helps
<asp:DropDownList ID="ddlFruits" runat="server">
<asp:ListItem Text="Please Select" Value=""></asp:ListItem>
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Get Selected Text Value" runat="server" OnClientClick="return GetSelectedTextValue()" />
<script type="text/javascript">
function GetSelectedTextValue() {
var ddlFruits = document.getElementById("<%=ddlFruits.ClientID %>");
var selectedText = ddlFruits.options[ddlFruits.selectedIndex].innerHTML;
var selectedValue = ddlFruits.value;
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
return false;
}
</script>
You can get the value from the list or the selected text (innerHTML) !

How to add text to asp:BoundField in GridView?

I have the following GridView in which data is being fed from the OleDB Database.
<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server">
<Columns>
...
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
...
</Columns>
</asp:GridView>
And I am reading the contents from the Database and printing in the GridView in the following manner:
protected void ShowGridView()
{
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string sqlQuery = "select * from ... ";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
}
What I want to do: I want to append % symbol to the contents of interestRate column in the GridView such that they should be displayed as 3% instead of 3. But the % symbol should not be inserted into the Database. In other words, the % symbol should only be used for display purposes in the GridView.
Depending on how you store the interest rate in the database will depend on which one of the below solutions remedy your question,
If the interest rates are formatted such that 0 = 0% and 1 = 100% you can use:
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" DataFormatString="{0:p}"/>
Documentation
Otherwise you will need to do a template
<columns>
<asp:TemplateField HeaderText="Interest Rate:">
<ItemTemplate>
<asp:Literal ID="IntRate" runat="server" Text='<%# Eval("InterestRate") + "%" %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</columns>
Updating answer as per comments below
protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
var row = GridViewSavingsTracker.Rows[index];
var interestRate = ((Literal row.FindControl("IntRate")).Text;
if (e.CommandName == "SomeCommand")
{
TextBoxInterestRate.Text = interestRate;
}
}

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

DropDownList with DataValueField and DataTextField asp.net C#

In my database, I entry CPVComID value from DropDownList (like
0,1,2,3) and display dataValueFiled value into DropDownList like
(-Select-, Conquest, CBC, Insight Management).
Error Message:
Exception Details: System.ArgumentOutOfRangeException: 'ddlCardCPVComName' has a SelectedValue which is invalid because itdoes not exist in the list of items. Parameter name: value
ASPX:
<asp:DropDownList ID="ddlCardCPVComName" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDSCPVCompanyName" DataTextField="CPVComName"
dataValueFiled="ddlCardCPVComName" Width="205px" DataValueField="CPVComID">
<asp:ListItem Value="0"> -SELECT- </asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
Code Behind:
private void getReceeivedCPV()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OptimaWebCustomerQueryCon"].ConnectionString))
{
conn.Open();
string str = #"SELECT CardCPVID, CardID,
CardCPVComName,
CardCPVSentDate, CardCPVStatus, CardCPVRcevDate, CPVRemarks FROM CC_CardCPV Where CardID LIKE '" + GVCPVReceived.SelectedValue + "'";
using (SqlCommand com = new SqlCommand(str, conn))
{
using (SqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
TextBox1.Text = Convert.ToString(dr[2]);
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
txtCardCPVSentDate.Text = Convert.ToDateTime(dr[3]).ToString("dd MMM yyyy");
ddlCardCPVStatus.SelectedItem.Value = Convert.ToString(dr[4]);
if (dr[5] != DBNull.Value)
{
txtCardCPVRcevDate.Text = Convert.ToDateTime(dr[5]).ToString("dd MMM yyyy");
}
else
{
txtCardCPVRcevDate.Text = "";
}
txtCPVRemarks.Text = Convert.ToString(dr[6]);
}
}
}
conn.Close();
}
}
What should I do? Please suggest me.
I can describe why this exception arises..In the below line of code you are setting a value to the dropdownlist ddlCardCPVComName..
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
Here the exception says that there is no such an item in the dropdownlist ddlCardCPVComName.So you must check when you bind the dropdownlist ddlCardCPVComName
that there exist the particular item which you are going to set..
Check this binding query and make sure that the desired items are bound to the datasource..
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
If am not wrong, Remove dataValueFiled="ddlCardCPVComName"(DropDown) from Your aspx code and execute.
I just change "dlCardCPVStatus.SelectedItem.Text = Convert.ToString(dr[4]);" and success to do this

Why can't I see ajax slide show images when I run?

I'd like to have an ajax slideshow on my web site. I get image urls from a database.
I think the code is right,but when I debug it my database photos are not shown.
I'm sure that my photos load completely.
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ToolkitScriptManager>
<div align="center">
<asp:Image ID="imgslides" runat="server" Height="400px"
ImageUrl="Gallery images/72007_205.jpg" BorderColor="Black"
BorderStyle="Solid" BorderWidth="5 px" />
<asp:Button ID="btnPrevious" runat="server" Text="Prev" />
<asp:Button ID="btnPlay" runat="server" Text="Play" />
<asp:Button ID="btnNext" runat="server" Text="Next" />
<ajax:SlideShowExtender ID="SlideShowExtender1"
runat="server" AutoPlay="true" Loop="true"
NextButtonID="btnNext"
PreviousButtonID="btnPrevious"
PlayButtonID="btnPlay"
PlayButtonText="Play"
StopButtonText="Stop"
TargetControlID="imgslides"
SlideShowServiceMethod="GetSlides"
SlideShowServicePath = "Slideshow.asmx">
</ajax:SlideShowExtender>
and this is my web service code Slideshow.asmx
public AjaxControlToolkit.Slide[] GetSlides()
{
SqlConnection myconn = new SqlConnection();
myconn.ConnectionString = "Data Source=PARISA-PC;Initial Catalog=Images;Integrated Security=True";
myconn.Open();
string selectCmd = "select * from images";
string countCmd = "select count(*) from images";
SqlCommand myCmd = new SqlCommand(selectCmd,myconn);
SqlCommand myCmd2 = new SqlCommand(countCmd,myconn);
int i = 0;
SqlDataReader dr = myCmd.ExecuteReader();
ArrayList ar = new ArrayList();
try
{
while (dr.Read())
{
ar.Add(dr.GetString(2));
}
}
catch (Exception)
{
throw;
}
myconn.Close();
AjaxControlToolkit.Slide[] Photos = new AjaxControlToolkit.Slide[ar.Count];
for(i=0 ; i< ar.Count ; i++){
Photos[i] = new AjaxControlToolkit.Slide(ar[i].ToString(),"image"+i.ToString(),"Booth's images");
}
return Photos;
}
[1]: http://i.stack.imgur.com/eMw4S.jpg
You have to use http handler or an aspx page (which showing images from database). Then you can send the Query String to that handler or aspx for a particular image from ajax slide web service. You can get enough examples in google about it.

Resources