i want use space inside string, i use this code:
var lst = Article.Select(a => new {a.ID, Name = " " + a.Name}).ToList();
gv.DataSource = lst.ToList();
gv.DataBind();
but its not working, with this code display name = " "Name.
and use this code:
var lst = Article.Select(a => new {a.ID, Name = " " + a.Name}).ToList();
gv.DataSource = lst.ToList();
gv.DataBind();
and with this code display name = " "Name.
please help me
Edit:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
...
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" ItemStyle-Width="300px" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
...
</asp:GridView>
Edit2:
Answer:
Link1
Link2
Thank you to all.
will this work?
string constructor that constructs a string from a character a repeat count:
var lst = Article.Select(a => new {a.ID, Name = new string(' ', 8) + a.Name})
.ToList();
UPDATE 1
set property, HtmlEncode=False
<asp:BoundField DataField="Name" HtmlEncode="False" />
and enclosed the value with <pre> tag
var lst = Article.Select(a => new {a.ID, Name = "<pre> </pre>" + a.Name})
.ToList();
I am assuming the gv is an asp.net gridview control and that all your whitespace is being merged when displayed in a browser.
So, try something like this
<asp:BoundField DataField="Name">
<ItemStyle CssClass="NameCol" />
</asp:BoundField>
and in your css
..NameCol
{
padding-left:50px;
}
Try this sample way
a.Name.ToString().PadLeft(10," ")
Must use ToString()
Edit Try this
a.Name.PadLeft(10,' ')
Related
My apsx
<section class="sec1" style="height:100vh;">
<link href="../Css/masterStyle.css" rel="stylesheet" />
<link href="../Css/cartStyle.css" rel="stylesheet" />
<h1>Cart</h1>
<p class="sec1_p1">Your Food</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableTheming="True" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:BoundField DataField="sno" HeaderText="sno" Visible="False" />
<asp:BoundField DataField="restaurantID" HeaderText="restaurantID" Visible="False" />
<asp:BoundField DataField="foodID" HeaderText="foodID" Visible="False">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="foodName" HeaderText="Name">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="foodPrice" HeaderText="Price">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="quantity" HeaderText="Quantity">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="totalPrice" HeaderText="Total ">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:CommandField DeleteText="Remove" ShowDeleteButton="True" />
</Columns>
<HeaderStyle BackColor="#52E770" ForeColor="White" />
</asp:GridView>
<asp:Label ID="test" runat="server" Text="Label"></asp:Label>
</section>
My .cs
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int sr;
int sr1;
string qdata;
string dtdata;
sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
dtdata = sr.ToString();
sr1 = Int32.Parse(qdata); //fixed
if (sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
//Label1.Text = "Item Has Been Deleted From Shopping Cart";
break;
}
}
for (int i = 1; i <= dt.Rows.Count; i++)
{
dt.Rows[i - 1]["sno"] = i;
dt.AcceptChanges();
}
Session["buyitems"] = dt;
Response.Redirect("AddToCart.aspx");
}
I have use Add Wacth in Visual Studio, and i get this result
1.$exception {"Input string was not in a correct format."} System.FormatException
2.qdata = cell.Text This expression causes side effects and will not be evaluated
3.TableCell cell = GridView1.Rows[e.RowIndex].Cells[0]; error CS1073: Unexpected token 'cell'
Instead of sr1 = Int32.Parse(qdata);
use TryParse as below (and you can combine condition in single if):
if (int.TryParse(qdata, out sr1) && sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
//Label1.Text = "Item Has Been Deleted From Shopping Cart";
break;
}
UPDATE:
Based on aspx code, I believe you are trying to read sno using the code:
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
But since that column's (or cell's) visible property is set to false, you will need to handle it differently. One of the ways is using DataKeyNames Property of GridView as shown below:
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
EnableTheming="True"
ShowFooter="True"
OnRowDeleting="GridView1_RowDeleting"
DataKeyNames = "sno" >
and in code behind, please remove the lines
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
and directly replace with below condition :
if (int.TryParse(GridView1.DataKeys[e.RowIndex].Value, out sr1) && sr == sr1)
{
// code to hanlde this case goes here
}
or since you know sno is int, you could directly cast to int. But it throws excpetion if its not int.
int sno = (int) GridView1.DataKeys[e.RowIndex].Value; // since Value is [object datatype][1]
If you want to use Cells property, then an option is update the visiable property of "sno" on GridView Row Creation event. If you want to go with this option, you need to remove visible=false from asp:BoundField definition as you will be setting it dynamically in Row Creation event.
This error means your string is not in a valid int format.
As pointed by Dai, you need to use TryParse:
var value = "test";
int number;
if (Int32.TryParse(value, out number))
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
value ?? "<null>");
}
You can also refer to Microsoft documentation here to have more details
You can get rid of the error by using Int32.TryParse
if(!Int32.TryParse(qdata, out sr1)){
MessageBox.Show(qdata + "is invalid number");
}
I want to create a table format with two columns where each row will have a ProductTitle and its corresponding URL.
I am using the following code which gives the info in table format. I displays entire anchor tag in second column.
But i want only the Text to be displayed as link in second column. On click of which it should open the URL page.
DataTable dt = new DataTable();
dt.Columns.Add("ProductTitle");
dt.Columns.Add("Link");
DataRow dr = dt.NewRow();
dr["ProductTitle"] = "GOOGLE";
dr["Link"] = "<" + "a href=\"" + "http://www.google.com" + "\">Google" + "</a>";
dt.Rows.Add(dr);
Gridview1.DataSource = dt;
Gridview1.DataBind();
Could anyone suggest.
You could modify the .aspx file as follows:
...
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ProductTitle" HeaderText="Product Title" />
<asp:BoundField DataField="Link" HtmlEncode="false" HeaderText="Link" />
</Columns>
</asp:GridView>
...
So, you should disable the automatic column generation by setting AutoGenerateColumns="false" and format the Columns section of the GridView. Please note the key element here for the link rendering, which is the HtmlEncode="false" attribute. You can also set everything in the code behind file:
GridView1.AutoGenerateColumns = false;
var productTitleField=new BoundField();
productTitleField.DataField="ProductTitle";
productTitleField.HeaderText="Product Title";
var linkField=new BoundField();
linkField.DataField="Link";
linkField.HeaderText="Link";
linkField.HtmlEncode=false;
GridView1.Columns.Add(productTitleField);
GridView1.Columns.Add(linkField);
Try this
dr["Link"] = "<a href='http://www.google.com'>Google</a>";
I tried
Label1.Text = "<a href='http://www.google.com'>Google</a>";
It works.
Second try :
We cannot save any thing else other than .NET types like string,int .etc ,so try asp:HyperLink like this
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductTitle")%>' NavigateUrl='<%# Eval("Link") %>'></asp:HyperLink>
</ItemTemplate>
and
dr["ProductTitle"] = "Goole";
dr["Link"] = "http://www.google.com";
There is actually a specific column designed just for what you want to do, it's the HyperLinkField column.
<asp:HyperLinkField
HeaderText="Header"
DataTextField="LinkText"
DataNavigateUrlFields="LinkURL"
DataNavigateUrlFormatString="http://google.com/q={0}" />
You can then ensure that your data source has the appropriate columns for the link text and navigate url fields.
You can configure it if you have a fixed text or fixed url to use the Text or NavigateURL properties instead of the Data... counterparts, and you can use or not use format strings as needed.
I have a GridView inside a UpdatePanel. In some cases, I have to show different columns in this GridView so I need to change the BoundFields that are specified in my aspx.
How can I change the BoundFields to make the GridView be filled for a different query and different fields ?
ASPX
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
CODE BEHIND
protected void btnSelecionarData_OnClick(object sender, EventArgs e)
{
string select = string.Empty;
select += "SELECT San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, San_Usuario.DescricaoCargo1, "
+ "CONVERT(varchar, San_Usuario.DataHora, 103) AS DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "FROM San_Usuario "
+ "JOIN San_Credenciada "
+ "ON San_Usuario.Credenciada_Id = San_Credenciada.Credenciada_Id "
+ "JOIN San_UsuarioCurso "
+ "ON San_Usuario.Usuario_Id = San_UsuarioCurso.Usuario_Id "
+ "WHERE San_Usuario.Provisorio = 1 "
+ "AND San_Usuario.Excluido = 0 "
+ "AND San_UsuarioCurso.DataCurso = '" + this.DtBusca.Value.ToString() +"' "
+ "GROUP BY San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, "
+ "San_Usuario.DescricaoCargo1, San_Usuario.DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "ORDER BY San_Usuario.DataHora ASC ";
dsGrid.ConnectionString = c.Con;
dsGrid.SelectCommand = select;
dsGrid.Dispose();
If I understand your query correctly, you want to change columns. A simple solution for this is that do not specify fields in your aspx page, just set AutoGenrateColumns = True in your grid view decleratoin
Your grid should look like
<asp:GridView ID="gv" runat="server" AutoGenrateColumns="True" />
// Now in your code behind just specify its DataSource property it will fill up with your desired columns.
// Your query should contain only those columns which you want to show
you can put GridView and Enable "AutoGenerateColumns=True" and for each case that you like fill grid view.
you can use this code for create ImageField Programmatically :
ImageField img = new ImageField();
img.HeaderText = "Pictuer";
img.DataImageUrlField ="Pic";
img.DataImageUrlFormatString = "images\\{0}";
GridView1.AutoGenerateColumns = false;
GridView1.Columns.Add(img);
I was able to get part of my answer from another question but cannot find a more specific bit of information that I need to finish.
I am trying to combine 2 fields into 1 like the above question but one of them is a GridHyperLinkColumn. I am using a GridItemDataBound event in the code behind to put 2 fields together like this:
protected void GridItemDataBound(object sender, GridItemEventArgs e) {
if (e.Item is GridDataItem) {
GridDataItem item = (GridDataItem)e.Item;
item["A"].Text = item["A"].Text + " /<br/>" + item["B"].Text;
item["C"].Text = item["C"].Text + " /<br/>" + item["D"].Text;
}
}
My UI shorten down for simplicity looks like this:
<Columns>
<telerik:GridBoundColumn UniqueName="A" DataField="A" />
<telerik:GridBoundColumn UniqueName="B" DataField="B" Visible="false" />
<telerik:GridHyperLinkColumn DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~.aspx?ID={0}" DataTextField="C" Text="{0}" UniqueName="C" />
<telerik:GridBoundColumn UniqueName="D" DataField="D" Visible="false" />
</Columns>
This works well for the first 2 columns that I combine into 1 (A & B).
However suppose item["C"] is a GridHyperLinkColumn. When I try the same code, it only shows / <D value>. Nothing shows up in front of the slash where "C" should be showing.
Is there a different property (instead of .Text) I should use or do I need to do it a different way?
There are a number of ways you could do this. One approach would be to use a template column as show below:
<Columns>
<telerik:GridTemplateColumn HeaderText="A and B">
<ItemTemplate><%# Eval("A") %>/<br /><%# Eval("B") %></ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="B and C">
<ItemTemplate><%# Eval( "C" ) %>/<br /><%# Eval("D") %></ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
If you're not interested in using a template column, you can get it to work the way you're doing it. The issue is that the GridHyperlinkColumn renders the link as a control (e.g. item["C"].Controls[0]) instead of directly in the Text property. Here is one way to get it to do what you want:
if (e.Item is GridDataItem) {
GridDataItem item = (GridDataItem)e.Item;
item["A"].Text = item["A"].Text + " /<br/>" + item["B"].Text;
Literal lit = new Literal();
lit.Text = " /<br/>" + item["D"].Text;
item["C"].Controls.Add( lit );
}
I have a GridView that gets populated with data from a SQL database, very easy.
Now i want to replace values in my one column like so......
If c04_oprogrs value is a 1 then display Take in the GridView.
If c04_oprogrs value is 2 then display Available in the GridView.
What code changes must i make to change to my code to display the new values.
My Grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="281px" Width="940px"
Font-Size="X-Small" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="c04_oprogrs" HeaderText="Order Progress"
SortExpression="c04_oprogrs" />
<asp:BoundField DataField="c04_orderno" HeaderText="Order No."
SortExpression="c04_orderno" />
<asp:BoundField DataField="c04_orddate" HeaderText="Date of Order"
SortExpression="c04_orddate" DataFormatString="{0:d/MM/yyyy}" />
<asp:BoundField DataField="c04_ordval" HeaderText="Order Value"
SortExpression="c04_ordval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_delval" HeaderText="Delivered Value"
SortExpression="c04_delval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_invval" HeaderText="Invoice Value"
SortExpression="c04_invval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_orddesc" HeaderText="Order Description"
SortExpression="c04_orddesc" >
<ControlStyle Width="300px" />
</asp:BoundField>
</Columns>
</asp:GridView>
My Page load
SqlConnection myConnection;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
//making my connection
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMRASConnectionString"].ConnectionString);
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate, c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND c04_oprogrs <> 9 ORDER BY c04_orddate DESC", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
Etienne
EDIT:
MY FINAL SOLUTION
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
string value = e.Row.Cells[0].Text;
if (value == "1")
{
e.Row.Cells[0].Text = "Take";
}
else if (value == "2")
{
e.Row.Cells[0].Text = "Available";
}
}
}
You can use the RowDataBound event for this. Using this event you can alter the content of specific columns before the grid is rendered.
To clarify a little. First you add a template column with a label to your grid view (see also the answer by ranomore):
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="myLabel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Next you implement the RowDataBound event (I haven't checked the code below, so it may contain some syntax errors):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
// some trial and error here to find the right control. The line
// below may provide the desired value but I'm not entirely sure.
string value = e.Row.Cells[0].Text;
// Next find the label in the template field.
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "1")
{
myLabel.Text = "Take";
}
else if (value == "2")
{
myLabel.Text = "Available";
}
}
}
You could use a template column and call a function in your code behind.
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#FieldDisplay(Eval("c04_oprogrs")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
then in your code behind do
protected string FieldDisplay(int c04_oprogrs)
{
string rtn = "DefaultValue";
if (c04_oprogrs == 1)
{
rtn = "Take";
}
else if (c04_oprogrs == 2)
{
rtn = "Available";
}
return rtn;
}
Without using a function. The ternary statement is in VB. If you have to nest another ternary statement to really test for 2 then it'd be easier to go with rwwilden's solution.
<asp:TemplateField HeaderText="Order Progress" SortExpression="c04_oprogrs" >
<ItemTemplate>
<asp:Label runat="server" ID="Label1" Text='<%# IIF(CInt(Eval("c04_oprogrs")) = 1, "Take", "Available") %>' />
</ItemTemplate>
</asp:TemplateField>
You could add a field in the SQL Statement
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate,
c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc ,
CASE c04_oprogrs WHEN 1 THEN "Take" WHEN 2 THEN "Available" ELSE "DontKnow" END AS
Status FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND
c04_oprogrs 9 ORDER BY c04_orddate DESC", myConnection);
And make that new field part of the BoundColumn in the markup.
Pardon my SQL syntax but I hope you get the idea.
EDIT: Do not use the syntax = '" + Session["CreditorNumber"] + "'.
See sql injection attack and how to avoid it using parameterized SQL.
This is the best efficient way.
Make a case in sql server view, like :-
select case <columnname>
when 1 then 'available'
when 0 then 'not available'
end as <columnname>
from <tablename>