i want to display some fields from my database in GridView but my problem is, it show all the field i want in one new field
this is my code
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
and this is c# code
GridView1.DataSource = (from x in db.Products
select x.name + x.phoneNumber + x.proviance + x.description + x.city + x.Address).ToList();
GridView1.DataBind();
how to display some fields of a table (not all fields) into gridView in c# in asp.net
With Respect
So by default GridView generates columns for all fields/columns in the data set it was given. To select what you see you need to turn this off and explicitly declare desired columns:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="name of the column in the data set"
HeaderField="header to show on the UI"/>
... and so on for other columns ...
</Columns>
</asp:GridView>
Related
I'm having problems retrieving the current row by changing the status of a DropDownList in the row. My code for the GridView is:
<asp:GridView ID="grdMappingList" runat="server" OnPageIndexChanging="grdMappingList_PageIndexChanging" AutoGenerateColumns="false" AllowPaging="true" PageSize="10" ShowHeaderWhenEmpty="true" UseAccessibleHeader="true" CssClass="table table-hover table-striped segment_list_tbl" >
<PagerStyle CssClass="grid_pagination" HorizontalAlign="Right" VerticalAlign="Middle" BackColor="#DFDFDF" />
<Columns>
<asp:BoundField HeaderText="Mapping Id" DataField="MAPPING_ID"></asp:BoundField>
<asp:BoundField HeaderText="PDM Name" DataField="PDM_NAME"></asp:BoundField>
<asp:BoundField HeaderText="PDM EntityID" DataField="PDM_ENTITY_ID" Visible="false"></asp:BoundField>
<asp:TemplateField HeaderText="Mapping Status" HeaderStyle-CssClass="width_120 aligned_center" ItemStyle-CssClass="width_120 aligned_center" Visible="true">
<ItemTemplate>
<asp:DropDownList id="ddlMappingStatus" runat="server" SelectedValue='<%# Bind("MappingCompleted") %>' OnSelectedIndexChanged="ddlMappingStatus_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Done" Value="DONE"></asp:ListItem>
<asp:ListItem Text="Not Done" Value="NOT DONE"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code behind is:
protected void ddlMappingStatus_SelectedIndexChanged(object sender, EventArgs e)
{
int MappingID = Convert.ToInt16(grdMappingList.SelectedRow.Cells[0].Text);
DropDownList ddgvOpp = (DropDownList)grdMappingList.SelectedRow.FindControl("ddlMappingStatus");
if (ddgvOpp.Equals("DONE"))
{
}
}
I am getting an error on this line:
DropDownList ddgvOpp (DropDownList)grdMappingList.SelectedRow.FindControl("ddlMappingStatus");
and this line:
int MappingID = Convert.ToInt16(grdMappingList.SelectedRow.Cells[0].Text);
It seems that I can't retrieve the values! I dont know why. When I choose a new status from the DropDownList, I want to get all the values of the row in order to update the record.
Unfortunately, SelectedRow does not mean what you think it means. It doesn't just simply mean the current row you are working on or the current row with the controls that you are using. That property must get set somehow. This is usually done through a "Select" button on the GridView, such as an <asp:ButtonField> with the command name "Select".
You really do not need this however. You just need the row you are working with. Since you are using the SelectedIndexChanged event of your DropDownList, you already have what you need. You just need to go about it a different way.
First, get the DropDownList. Then get the row of the DropDownList. Now do whatever you need with the row.
But, from your code, it looks like you may not even need the row. You just need the value of the DropDownList. So you could skip that all together. But if you do need the row, here is how you would do that too.
protected void ddlMappingStatus_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlMappingStatus = (DropDownList)sender;
if(ddlMappingStatus.SelectedItem.Text.ToUpper() == "DONE")
{
}
GridViewRow row = (GridViewRow)ddlMappingStatus.NamingContainer;
}
Now when you use <asp:BoundField> controls in your GridView, getting their values isn't very clean. You are forced to hardcode the column index like you were doing:
GridViewRow row = (GridViewRow)ddlMappingStatus.NamingContainer;
String mappingID = row.Cells[0].Text;
I tend to prefer using <asp:TemplateField> controls so I can use FindControl() to get what I am after. This prevents any reordering of the columns from breaking the code, as you'd have to hardcode different indexes. So for example, to find that DropDownList (since it already is a <asp:TemplateField>), you'd do something like this:
DropDownList ddlMappingStatus = (DropDownList)row.FindControl("ddlMappingStatus");
I have Gridview to show all the data from a datatable.
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True" Width="100%" PageSize="20"
AutoGenerateColumns="true"
CssClass="applicationList-grid" CellPadding="4" ForeColor="#333333" EmptyDataText="No Data!">
</asp:GridView>
and the gridview binded by
string sql = "SELECT * from ApplicationForm";
DataTable dt = GetDataTable(connectionString, sql);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
There is some date fields. The date showing like 04/03/2014 00:00:00 in gridview. I want to format the date with only date no time.
I just try dataformatstring="{MM/dd/yyyy} but it is not working.
You can convert it by below usage-
<span><%# Eval("columnname", "{0:MM/dd/yyyy}")</span>'
Or in SQL
CONVERT( VARCHAR(10), "columnname" ,110)
Note- 110 is the country code.
You can do like this inside your <asp:GridView>
<asp:boundfield datafield="Date_Column" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />
Make sure that HtmlEncode is set to False, otherwise it will not work
put :
DataFormatString="{0:MM-dd-yyyy}"
and :
htmlencode="false"
on your bound field tag. You can see the format which you want.
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 that gets data from an sqldatasource and as a results gets 3 columns from an SQL query: ID, description and price.
What I want to do is adding another column with an hyperlink in the format of page.aspx?id=x where x is the ID code from the first column. This for each row in the table.
I've been looking all morning for how to do this, all I got is that I have to manage the RowDataBound event and use an hyperlinkfield but couldn't find anything else that explained how they actually work together, even the msdn article is kind of vague on the subject or just doesn't have any relevant help for my specific case as I'm managing the gridview from the code-behind.
Also haven't been able to figure how to access strings from the other columns, since it's what I need to insert in the resulting hyperlink.
Here's what I got so far for the creation of the gridview:
private void FillGrid(string qid)
{
SqlDataSource1.ConnectionString = Connessione.connectionString;
SqlDataSource1.SelectCommand = "SELECT art_tessuto_articolo, art_tessuto_descrizione, lipre_prezzo FROM lipre INNER JOIN listini_tessuti ON lipre.lipre_codice = listini_tessuti.listini_codice INNER JOIN art_tessuti ON lipre.lipre_articolo = art_tessuti.art_tessuto_articolo WHERE lipre_codice = #qid AND lipre_prezzo <> 0";
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("qid", qid);
GridView1.AllowPaging = true;
GridView1.PageSize = 500;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
This should do the job.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlControl = new HyperLink();
hlControl.Text = e.Row.Cells[0].Text;
hlControl.NavigateUrl = "page.aspx?id=" + e.Row.Cells[0].Text;
e.Row.Cells[3].Controls.Add(hlControl);
}
}
Use HyperlinkField
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperlinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="page.aspx?ID={0}" />
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" Text="VisibleText" NavigateUrl='<%# Eval(columnname) %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
in a datatable you can rename column as follows:
dt.Column[0].ColumnName="name";
Is it possible to do something similar with list<MyType>? I need to retrun list of objects with modified column names. to bind to a gridview some special way.
You can go with anonymous types:
var yourList = new List<MyType>{ ... };
var newList = yourList.Select( i=> new { NewColumn = i.OldName });
In the asp.net gridviews you can use Bound Fields to Bind Properties and Set the Column Headers to whatever you want
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="MyProperty" HeaderText="My Custom Column Heaer" />
</Columns>
</asp:GridView>
Just make sure the MyProperty exists on the MyType and you should be good.