How to display certain selected words bolder in asp:hyperlink text - c#

I have a asp:repeater control on my .aspx and in the code behind I am binding its datasource to a Collection of type KeyValuePair[]<Literal,String>. I was choosing literal so that I could surround selected words in literal text with <strong> or <b> html tag. Well I succeeded in doing it but I am not finding a way to display the literal text in the asp:hyperlink's Text part of asp:repeater
My .aspx code is as follow:
<asp:Repeater ID="repLinks" runat="server">
<ItemTemplate>
<div onclick="window.open('<%# ((KeyValuePair<Literal,string>)Container.DataItem).Value %>','_blank');">
<div>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# ((KeyValuePair<Literal,string>)Container.DataItem).Value %>" Text="<%#((KeyValuePair<Literal,string>)Container.DataItem).Key.Text %>"
Font-Size='Large' ForeColor='Blue' Font-Names="Open Sans" CssClass="linkstyle" />
<br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I need help on how to display the .Key.Text part in asp:Hyperlink.
I added the keyValuePair as follow:
char[] seperator = { ' ' };
String[] explodedString = Results1[index].Key.Split(seperator);
List<String> Query= new List<string>(TextBox1.Text.Trim().ToLowerInvariant().Split(seperator,StringSplitOptions.RemoveEmptyEntries));
for (int i = 0; i < explodedString.Length; i++)
{
if (Query.Contains(explodedString[i].ToLowerInvariant()) == true)
{
explodedString[i] = "<strong>" + explodedString[i] + "<strong>";
}
}
Literal temp = new Literal();
temp.Text = explodedString.ToString();
TryCurrentWindow[index] = new KeyValuePair<Literal, string>(temp, Results1[index].Value);
Here TryCurrentWindow is the KeyValuePair[] and explodedstring[] is the text string splitted by '' char which I want to modify and Query[] is list of my keyWords

Problem:
You are not closing <strong> tag like this </strong>.
You are simply doing ToString() to string[] array.
Updated this line:
explodedString[i] = "<strong>" + explodedString[i] + "</strong>";
Also change below code:
Literal temp = new Literal();
temp.Text = explodedString.ToString();
With this:
Literal temp = new Literal();
temp.Text = string.Join(" ", explodedString);
As indexes are modified in the string[] array. You are required to join array to get modified string[] array.
Updated Code Snippet:
char[] seperator = { ' ' };
String[] explodedString = Results1[index].Key.Split(seperator);
List<String> Query= new List<string>(TextBox1.Text.Trim().ToLowerInvariant().Split(seperator,StringSplitOptions.RemoveEmptyEntries));
for (int i = 0; i < explodedString.Length; i++)
{
if (Query.Contains(explodedString[i].ToLowerInvariant()) == true)
{
explodedString[i] = "<strong>" + explodedString[i] + "</strong>"; //changed
}
}
Literal temp = new Literal();
temp.Text = string.Join(" ", explodedString); //changed
TryCurrentWindow[index] = new KeyValuePair<Literal, string>(temp, Results1[index].Value);

Related

Set Height of a listbx fit to content

I have to set a list box which shows data from database column . Each time different length of data will come to list-box. so according to this I have to change its height fit to content . How is it ?
<asp:ListBox ID="ListBox1" runat="server" BackColor="White" Height="14000px"
Width="1312px"></asp:ListBox>
while (dr.Read())
{
string poem = dr[0].ToString();
byte[] newFileData = Encoding.ASCII.GetBytes(poem);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
string[] poem_details = fileString.Split(new string[] { " ", "\n" }, StringSplitOptions.None);
foreach (var line in score_details)
{
ListBox1.Items.Add(line);
}
}
Try this-
Listbox.rows = Listbox.Items.count
OR
you can also set size attribute as follows-
$(document).ready(function() {
$('#<%=this.ListBox1.ClientID%>').attr('size', $('#<%=this.ListBox1.ClientID%> option').length);
});

avoid double when save button is click

I use C# 4.0 and SQL Server 2008 R2 and I've a simple button click that call a function that save the data into database and redirect the page.
The probleme is when the client click more than one on this save button, then i save more than one item also into the database.
I want to avoid the client make a mistake, that meant the client can only do 1 clic = 1 save data.
<dx:ASPxButton ID="ASPxButton_save" runat="server" Image-Url="~/images/Icon/Good-or-Tick-icon.png" Text="Enregistrer" Width="110px" onclick="ASPxButton_save_Click" ValidationGroup="Savebouton">
</dx:ASPxButton>
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
string ErrPos = "";
try
{
ErrPos = "Affct CP DEST";
string FA_Choisi = ASPxTextBox_CP_dest.Text.Substring(0, 2);
string CLIENT_de_FA = ClientId.Substring(0, 2);
List<string> ClotList_FA = new List<string>();
ErrPos = "Affct Trans";
foreach (DataRow myRow in oOrdre_BL.Get_Tranporteur(ClientId).Tables["Le_Transporter"].Rows)
{
ClotList_FA.Add(myRow["LIBELLE"].ToString());
}
Pers_Client_Entrp oPersclientEntrp = GetOPersclientEntrp();
Pers_Ordre oPersOrdr = new
.......
if (ASPxCheckBox_NewDesti.Checked)
{
string ResTemp = oDest_BL.Compare_Dest(ClientId, ASPxTextBox_Desti_ID.Text, ASPxTextBox_RS_NOM_dest.Text, ASPxTextBox_ADRESSE_dest.Text);
if (!String.IsNullOrWhiteSpace(ResTemp))
{
lbl_err.Text = ResTemp;
}
else
{
Pers_Dest TheDest = new Pers_Dest();
TheDest.CodeDest = ASPxTextBox_Desti_ID.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.CodeClient = ClientId;
TheDest.RaisonSoc = ASPxTextBox_RS_NOM_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Adresse = ASPxTextBox_ADRESSE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Cp = ASPxTextBox_CP_dest.Text;
TheDest.Ville = ASPxComboBox_VILLE_dest.Text;
TheDest.Pays = ASPxComboBox_PAYS_dest.Value.ToString();
TheDest.Tel = ASPxTextBox_TEL_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Fax = ASPxTextBox_FAX_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Email = ASPxTextBox_EMAIL_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Insee = ASPxTextBox_INSEE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Siret = ASPxButton_SIRET_dest.Text.Replace('-', ' ').Replace('\'', ' ');
oDest_BL.CrUp_Dest(TheDest, true);
oPersOrdr.Ville = ASPxComboBox_VILLE_dest.Text;
Save_Part(oPersOrdr, oPersclientEntrp, OrdreID);
}
}
else
{
oPersOrdr.Ville = ASPxTextBox_VILLE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
Save_Part(oPersOrdr, oPersclientEntrp, OrdreID);
}
catch (Exception ex)
{
lbl_err.Text = ex.Message;
if (ex.InnerException != null) { lbl_err.Text += "-->" +ex.InnerException.Message; }
Outils_IHM.SendingEmail("Save Odre --> Err Position: " + ErrPos + "-----" + lbl_err.Text, ClientId);
}
private void Save_Part(Pers_Ordre oPersOrdr, Pers_Client_Entrp oPersclientEntrp, string OrdreID)
{
oOrdre_BL.SaveUpdt_Ordre_BL(oPersOrdr, OrdreID);
string QuelleID = TempId;
if (!String.IsNullOrWhiteSpace(OrdreID))
{ QuelleID = OrdreID; }
if (oPersclientEntrp.TypPrint == "Zebra")
{ Response.Redirect("../Print/BonEticket_Web.aspx?ConnPrint=UnDirect&OdreID=" + QuelleID + "&CountOrdre=" + ASPxTextBox_NBR_COLIS.Text + "&TypeAR=" + TypeEnlev, false); }
else
{ Response.Redirect("../Print/BonEticket_Web.aspx?OdreID=" + QuelleID + "&CountOrdre=" + ASPxTextBox_NBR_COLIS.Text + "&TypeAR=" + TypeEnlev, false); }
Context.ApplicationInstance.CompleteRequest();
}
I have an idea, when the user clic this button, than it will call client side function to disable it. But i don't know how and if it work as i want to.
you can use the below mentioned code as ref.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
var submit = 0;
function CheckIsRepeat() {
if (++submit > 1) {
alert('An attempt was made to submit this form more than once; this extra attempt will be ignored.');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="return CheckIsRepeat();" />
</div>
</form>
</body>
</html>
Before saving data to database disbale the button , then save the data, then clear the controls & then again enable the button.
<dx:ASPxButton ID="ASPxButton_save" runat="server" Image-Url="~/images/Icon/Good-or-Tick-icon.png" Text="Enregistrer" ClientInstanceName="ASPxButton_save" Width="110px" onclick="ASPxButton_save_Click" ValidationGroup="Savebouton">
<ClientSideEvents Click ="function(s,e) { MyBtnClick(s,e); } " />
</dx:ASPxButton>
function MyBtnClick(s, e) {
if (ASPxClientEdit.AreEditorsValid())
ASPxButton_save.SetVisible(false);
}

How to remove span when generating HtmlGenericControls from Code Behind

I have this peace of code which generates a dropdown menu, Unfortunately I'm running into issues because span tags are being generated at the creation of each HtmlGenericControl.
This is my code to generate the HtmlGenericControls:
string _touid = Request.QueryString["touid"];
string _group_array = Connections.isp_GET_VALUE("TRSTR", "", "", "");
string _tour_array = _group_array.Replace(" ", "");
HtmlGenericControl _ul = new HtmlGenericControl();
_ul.InnerHtml = "<ul class=\"dropdown-menu\">";
tour_holder.Controls.Add(_ul);
string[] groups = _tour_array.Split(',');
foreach (string group in groups)
{
string _tournoment_string = Connections.isp_GET_VALUE("TRNAM", group, "", "");
HtmlGenericControl _li = new HtmlGenericControl();
_li.InnerHtml = "<li>" + _tournoment_string + "</li>";
tour_holder.Controls.Add(_li);
}
HtmlGenericControl _ul_ = new HtmlGenericControl();
_ul_.InnerHtml = "</ul>";
tour_holder.Controls.Add(_ul_);
Below is the HTML output:
<span><ul class="dropdown-menu"></span>
<span><li>FIFA World Cup Brasil 2014 </li>
</span>
<span><li>FIFA U-20 World Cup New Zealand 2015 </li></span>
<span><li>FIFA Woman's World Cup Canada 2015 </li></span>
<span></ul></span>
</div>
How can I remove the span tag?
A similar question has been asked here.
Try passing the HTML tag the constructor instead of using the InnerHtml property like that:
HtmlGenericControl _ul = new HtmlGenericControl("ul");

FileUpload on listview

I have ListView that display info from XML and to save to server from FileUpload that are on this ListView. I dont have problem to write to the XML, the problem is on save the FileUpload to folder.
I belive that i have mistake that i not seperate the listview to itemtemplate and insertemplate and edit...It must to? because the title going to correct place on XML, and even file name. but the file not saved to the folder.
For most tests i did - nothing happent after click on "update" BTN. when i add the int "i" to the items[i] somtimes it just update the xml without saving the file, and sometimes i get error of "out of index".
What is wrong?
ASPX code
<h2><asp:Label ID="LBL_number" runat="server" Text='<%#XPath("id") %>'></asp:Label></h2>
<h2>Small Image</h2> <asp:Image Width="100" CssClass="ltr" runat="server" ID="TB_small" ImageUrl='<%# XPath("small_image_url") %>'></asp:Image><asp:FileUpload ID="FU_small" runat="server" />
<br /><br /><br />
<h2>Big Image</h2> <asp:Image Width="300" CssClass="ltr" runat="server" ID="TB_big" ImageUrl='<%#XPath("big_image_url") %>'></asp:Image><asp:FileUpload ID="FU_big" runat="server" />
<br /><br />
<h2>Title</h2> <asp:TextBox runat="server" ID="TB_title" Text='<%#XPath("title") %>'></asp:TextBox>
<br /><br /><br />
<asp:Button CssClass="btn" ID="Button1" CommandArgument='<%#XPath("id") %>' runat="server" OnClick="update" Text="Update" />
<br />
<asp:Button ID="Button3" CssClass="btn" CommandArgument='<%#XPath("id") %>' runat="server" CommandName="del" OnClick="del" Text="מחק" />
<br /><br />
<br /><br />
</ItemTemplate>
</asp:ListView>
<asp:XmlDataSource ID="XDS_data" runat="server"
DataFile="~/App_Data/AM_data.xml" XPath="/Data/datas/data">
</asp:XmlDataSource>
C# Example only with the small file upload.
protected void update(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
var FU_small1 = (FileUpload)myButton.FindControl("FU_small");
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
if (fu2.HasFile == true)
{
fu2.SaveAs(Server.MapPath("~/imgs/data/big" + filename_small.ToString() + extenstion_small.ToString()));
}
var TB_title = (TextBox)myButton.FindControl("TB_title");
string myString3 = TB_title.Text;
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Response.Redirect(Request.RawUrl);
}
There are several problems with your update method:
You need to find control inside container, not inside button. *Wrong approach : * var TB_title = (TextBox)myButton.FindControl("TB_title");
There's no guarantee that id will match ListView's item index. *Wrong approach : * FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
etc.
I would suggest to change the method to this:
protected void update(object sender, EventArgs e)
{
int index = 0;
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
ListViewItem lvwItem = (ListViewItem)myButton.NamingContainer;
FileUpload FU_small1 = myButton.FindControl("FU_small") as FileUpload;
if (FU_small1 != null && int.TryParse(myButton.CommandArgument, out index))
{
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title!= null ? TB_title.Text : string.Empty;
if (FU_small1.HasFile == true)
{
FU_small1.SaveAs(Server.MapPath("~/imgs/data/small/" + filename_small + extenstion_small));
}
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + index + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/small/" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
Response.Redirect(Request.RawUrl);
}
And here's a test project I have used to test this.
Finnaly, "foreach" solved it
protected void update(object sender, EventArgs e)
{
//Get xml file
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
//Set button for index it later by CommandArgument
Button myButton = (Button)sender;
foreach (ListViewItem item in LV_data.Items)
{
//Findcontrol of 2 fileupload on listview
FileUpload FU_small1 = (FileUpload)item.FindControl("FU_small1");
FileUpload FU_big1 = (FileUpload)item.FindControl("FU_big1");
//Check if are has file.
if (FU_small1.HasFile && FU_big1.HasFile)
{
//Get extension and genereate random filenames (for avoid ovveride)
FileInfo small_info = new FileInfo(FU_small1.FileName);
FileInfo big_info = new FileInfo(FU_big1.FileName);
string ext_small = small_info.Extension;
string ext_big = big_info.Extension;
string filename_small = Guid.NewGuid().ToString();
string filename_big = Guid.NewGuid().ToString();
//Set i value by button CommandArgument (look on aspx on question)
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
//Get title from TextBox and set string from it
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title != null ? TB_title.Text : string.Empty;
//Save the files from the fileuploads we found, and write it on xml
FU_small1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/thumbs/" + filename_small + ext_small));
FU_big1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/big/" + filename_big + ext_big));
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/thumbs/" + filename_small + ext_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + ext_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
}
// Refresh the page
Response.Redirect(Request.RawUrl);
}

Error with regex Input string was not in a correct format

Hi guys I have string <span class="lnk">Участники <span class="clgry">59728</span></span>
I parse it
string population = Regex.Match(content, #"Участники <span class=""clgry"">(?<id>[^""]+?)</span>").Groups["id"].Value;
int j = 0;
if (!string.IsNullOrEmpty(population))
{
log("[+] Группа: " + group + " Учасники: " + population + "\r\n");
int population_int = Convert.ToInt32(population);
if (population_int > 20000)
{
lock (accslocker)
{
StreamWriter file = new StreamWriter("opened.txt", true);
file.Write(group + ":" + population + "\r\n");
file.Close();
}
j++;
}
}
But when my string is ><span class="lnk">Участники <span class="clgry"></span></span> I receive an exaption "Input string was not in a correct format".
How to avoid it?
Instead of Regex use a real html parser to parse htmls. (for ex, HtmlAgilityPack)
string html = #"<span class=""lnk"">Участники <span class=""clgry"">59728</span>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var list = doc.DocumentNode.SelectNodes("//span[#class='lnk']/span[#class='clgry']")
.Select(x => new
{
ParentText = x.ParentNode.FirstChild.InnerText,
Text = x.InnerText
})
.ToList();
Trying to parse html content with regex is not a good decision. See this. Use Html Agliliy Pack instead.
var spans = doc.DocumentNode.Descendants("span")
.Where(s => s.Attributes["class"].Value == "clgry")
.Select(x => x.InnerText)
.ToList();

Categories