Double columns in GridView, building from code behind in C# - c#

I'm trying to fill a GridView with a RadioButton and data from a CreditCardList. However, it's doubling the columns for each field... one full set of columns then another complete set (sans the RadioButton) I've checked creditCardList.items.Count and made sure it's just 1 (which it is). What am I doing wrong?
aspx:
<asp:GridView ID="gvCards" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Sel">
<ItemTemplate>
<asp:RadioButton ID="Sel" runat="server" GroupName="rad" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Customer ID" />
<asp:BoundField DataField="Card ID" HeaderText="Card ID" />
<asp:BoundField DataField="Card Number" HeaderText="Card Number" />
<asp:BoundField DataField="Expiration" HeaderText="Expiration" />
<asp:BoundField DataField="State" HeaderText="State" />
</Columns>
</asp:GridView>
Code behind:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Customer ID", typeof(string));
dt.Columns.Add("Card ID", typeof(string));
dt.Columns.Add("Card Number", typeof(string));
dt.Columns.Add("Expiration", typeof(string));
dt.Columns.Add("State", typeof(string));
for (var i = 0; i < creditCardList.items.Count; i++)
{
DataRow row1 = dt.NewRow();
row1["Name"] = creditCardList.items[i].first_name + " " + creditCardList.items[i].last_name;
row1["Customer ID"] = creditCardList.items[i].external_customer_id;
row1["Card ID"] = creditCardList.items[i].id;
row1["Card Number"] = creditCardList.items[i].number;
row1["Expiration"] = creditCardList.items[i].expire_month + "/" + creditCardList.items[i].expire_year;
row1["State"] = creditCardList.items[i].state;
dt.Rows.Add(row1);
}
gvCards.DataSource = dt;
gvCards.DataBind();
Output:
Sel Name Card ID Card Number Expiration State Name Customer ID Card ID Card Number Expiration State
Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok Steve Ricketts %40LDN CON CARD-3F3 xxxxxxxxxxx1000 3/2020 ok

set AutoGenerateColumns="false" .
<asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="false">
<Columns>
</Columns>
</asp:GridView>
Remarks
When the AutoGenerateColumns property is set to true, an AutoGeneratedField object is automatically created for each field in the data source. Each field is then displayed as a column in the GridView control in the order that the fields appear in the data source. This option provides a convenient way to display every field in the data source; however, you have limited control of how an automatically generated column field is displayed or behaves.
Instead of letting the GridView control automatically generate the column fields, you can manually define the column fields by setting the AutoGenerateColumns property to false and then creating a custom Columns collection. In addition to bound column fields, you can also display a button column field, a check box column field, a command field, a hyperlink column field, an image field, or a column field based on your own custom-defined template.

Related

If date column (column A) in gridview is today's date, show expired in column B

I have a gridview that is getting data from a stored procedure. Column A is a date field. Column B has the text active (for all rows). However, I would like to change the text of 'active' (in the status column) to 'expired' based on the date - so if it's today's date or older, show expired. I know I could execute a job on the SQL server to change the column before importing into my table. However, I would like to only change the text and not alter the DB if possible. So, how would I manipulate the active column to show expired based on today's date.
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
tblMytable.DataSource = dt;
tblMytable.DataBind();
con.Close();
}
The webform:
<asp:GridView ID="tblMytable" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateField" HeaderText="Date" />
<asp:BoundField DataField="Status" HeaderText="Status" />
</Columns>
</asp:GridView>
If you make it a TemplateField you have much more control over the data and you can then use a Ternary operator to apply some logic.
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("DateField")) < DateTime.Now ? "Expired" : "Active" %>
</ItemTemplate>
</asp:TemplateField>

formatting the gridview asp.net

Font-Names = "Arial" >
<Columns>
<asp:BoundField DataField = "itemId" ControlStyle-Width="100" HeaderText = "ID" />
<asp:BoundField DataField = "itemDesc" ControlStyle-Width="100" HeaderText = "Image Desc" />
<asp:ImageField DataImageUrlField="itemImage" ControlStyle-Width="200"
ControlStyle-Height = "200" HeaderText = "Preview Image"/>
</Columns>
</asp:GridView>
I have this gridview to display some data from database, how do I do, if I want the data to display like a table such as 3 column in a row and after 3 it will go to next row like a 3x4 table, it will display a next page button to display more data. Example like the e-commerce website they display a few product in the row and continue to display some product in the next row, and a next page button is provided.

Checkbox field not visible in gridview

I am working in asp.net. Trying to display data in gridview retrieved from a web service. I want five fields in gridview, one checkbox field and other four are values from service i.e.
CheckboxField,FirstName,LastName,OffenseName,FineAmount
1 ) Following is gridview code, that i just dragged and dropped into page
<asp:GridView ID="GridView1" runat="server">
<HeaderStyle BackColor="#CCFF33" />
</asp:GridView>
2 ) Following is my method that i call, to create fields in a DataTable, which i will bind to gridview later.
DataTable table = new DataTable();
table.Columns.Add("Select", typeof(CheckBox)); // i think problem is here
table.Columns.Add("FirstName", typeof(string));
table.Columns.Add("LastName", typeof(string));
table.Columns.Add("OffenseName", typeof(string));
table.Columns.Add("FineAmount", typeof(string));
3) Following is code to that populates the data table, with data
for (int i = 0; i < noOfContacts; i++)
{
object[] rowVals = new object[5];
rowVals[0] = giveCheckBox(i); // this method is declared below, which gives me a checkbox with unique id
rowVals[1] = listOfContacts[i].FirstName;
rowVals[2] = listOfContacts[i].LastName;
rowVals[3] = listOfCharges[j].GHQOffenseId;
rowVals[4] = listOfCharges[j].GHQFineAmount;
table.Rows.Add(rowVals);
}
GridView1.DataSource = table;
GridView1.DataBind();
4) This is method that gives me a checkbox, with unique id
public CheckBox giveCheckBox(int i)
{
CheckBox chk = new CheckBox();
chk.ID = "chk_" + i;
chk.Text = "Pay";
return chk;
}
Problem is that when i run the program, it only display four fields but not first checkbox field. I want to dispay that must.
But if i add checkbox field in designing view, (click arrow on gridview, click Add New Fields), then it throws exception at binding line i.e.
GridView1.DataBind();
Please guide me how to make checkbox field visible.
You can insert all your fields in design like code below :
<asp:GridView ID="GridView1" runat="server">
<HeaderStyle BackColor="#CCFF33" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk_box" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="OffenseName" HeaderText="OffenseName" />
<asp:BoundField DataField="FineAmount" HeaderText="FineAmount" />
</Columns>
</asp:GridView>
and for the code behind:
DataTable table = new DataTable();
for (int i = 0; i < 2; i++)
{
DataRow dr = table.NewRow();
dr["FirstName"] = "Ahmed";
dr["LastName"] = "Ahmed";
dr["OffenseName"] = "Ahmed";
dr["FineAmount"] = "Ahmed";
table.Rows.Add(dr);
}
GridView1.DataSource = table;
GridView1.DataBind();
Instead adding the checkbox to your table(which is wrong anyway) add a template field to the gridview as below. Also specify AutoGenerateColumns=true. Then remove all the code in your codebehind which tries to add checkbox column to the table and gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True">
<Columns>
<asp:TemplateField ShowHeader="False" >
<ItemTemplate>
<asp:CheckBox ID="checkBoxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<HeaderStyle BackColor="#CCFF33" />
</Columns>
</asp:GridView>
Yes, you're right the problem lies exactly in that code snippet. Replace the following line
table.Columns.Add("Select", typeof(CheckBox));
with this one
table.Columns.Add("Select", typeof(bool));

How to create a link text in a table using c#

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.

Unable to set column elements as hyperlink

I'm trying to set the first column elements as hyperlinks redirecting to another page..but somehow it doesn't seem to work no matter what I try.
reportTable.Rows[i].Cells[1].Text = report.reportId.ToString();
TableCell tCell = new TableCell();
tCell.Controls.Add(new LiteralControl(" report.reportId.ToString ()"));
// Create Hyperlink Web Server control and add to cell
System.Web.UI.WebControls.HyperLink h = new HyperLink();
h.Text = reportTable.Rows[i].Cells[1].Text = report.reportId.ToString();
h.NavigateUrl = "~/manage.aspx";
tCell.Controls.Add(h);
reportTable.Rows[i].Cells[2].Text = bench.mechId;
reportTable.Rows[i].Cells[3].Text = bench.elecId;
reportTable.Rows[i].Cells[4].Text = bench.name;
asp.net Grid and data controls are very good for data binding.
Also they provide Item templates that can be customized to include links, drop down lists, etc.
Do not populate your grid by manually creating all the controls. That totally defeats the purpose of using a grid.
e.g:
<asp:GridView ID="ReportsGridView"
DataSourceID="ReportsDataSource"
AllowPaging="true"
AutoGenerateColumns="false"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server"
ID="RedirectButton"
CommandName="Manage"
PostBackUrl="~/manage.aspx"
Text="Manage" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name"
HeaderText="Report Name"/>
</Columns>
</asp:GridView>

Categories