Checkbox field not visible in gridview - c#

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));

Related

Double columns in GridView, building from code behind in 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.

add textbox in DataTable aspx.net

i want to add textBox into dataTable row.I dont know how to do that.Is it possible to add textBox to a dataTable?First it give me this error:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
Here is my code:
Markup:
<asp:GridView ID="GridView2" runat="server" ShowHeader="false" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<ItemTemplate >
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
private void AddNewRecordRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "table";
dt.Columns.Add(new DataColumn("Zabeleshka", typeof(TextBox)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["marks"] = dt;
if (ViewState["marks"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["marks"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
drCurrentRow["Zabeleshka"] = TextBox1.Text;
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["marks"] = dtCurrentTable;
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
}
You can add a textbox into a gridview no problem then find it from the code behind in the RowDataBound Grid Method. Your problem is more than likely the fact that you have closed your TemplateField and have not opened one. You need to add
<asp:TemplateField>
above your
<ItemTemplate>.
As your markup code i think you want Text Box inside Gridview with containing some value into that,
for this,
first of all your markup is not correct, the correct one is,
<asp:GridView ID="GridView2" runat="server" ShowHeader="false" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField> <%-- you have not opened it in your markup --%>
<ItemTemplate >
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind,
to get the textbox value you need
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
edited,
in your code,
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
drCurrentRow["Zabeleshka"] = TextBox1.Text;
the for loop condition is (i <= dtCurrentTable.Rows.Count)
you should try this (i < dtCurrentTable.Rows.Count)
because the counting of row is start from 0 and thats why you getting index out of range error.

Binding a DataTable to Gridview - Doesn't display on Web Page

The issue I'm having is getting my DataTable to display in the Gridview. I have searched the web for answers, but everything I have found relates to binding database information right after a query is executed. I have to manipulate the data that I get from the query to display an average so everything in my datatable is stored in local variables and containers. Here is the code for the gridview on the aspx page and the block that is adding my rows to the table and binding the table to the girdview. any help on why it isn't displaying on the web would be appreciated. I'm using VS2012 and .Net v4
DataRow newRow;
for (int i = 0; i < portcount; i++)
{
newRow = averageTable.NewRow();
newRow["port_num"] = i+1;
newRow["port_status"] = currentstat[i]; //this is a list<Int32>
newRow["average_uptime"] = (statusCalc[i] / counter) * 100;
//statusCalc is an int array
averageTable.Rows.Add(newRow);
}
statusRdr.Close();
GridView completeView = new GridView();
this.completeView.Visible = true;
completeView.DataSource = averageTable;
completeView.DataBind();
<asp:Content ID="bodyContnet" ContentPlaceHolderID="cphContent" runat="server">
<asp:GridView ID="completeView" runat="server" AutoGenerateColumns="False" ViewStateMode="Enabled" ForeColor="WhiteSmoke" Width="51%" Height="204px">
<Columns>
<asp:BoundField DataField="port_num" HeaderText="Port" />
<asp:BoundField DataField="port_status" HeaderText="Status" />
<asp:BoundField DataField="average_uptime" HeaderText="Average Uptime" />
</Columns>
</asp:GridView>
<br />
<br />
<asp:Label ID="message" runat="server" ForeColor="WhiteSmoke" Text="Port Status Table"></asp:Label>
</asp:Content>
You don't need to re-create the GridView, it's already on the page and visible by default. Remove the lines that do this so your code looks like this:
DataRow newRow;
for (int i = 0; i < portcount; i++)
{
newRow = averageTable.NewRow();
newRow["port_num"] = i+1;
newRow["port_status"] = currentstat[i]; //this is a list<Int32>
newRow["average_uptime"] = (statusCalc[i] / counter) * 100;
//statusCalc is an int array
averageTable.Rows.Add(newRow);
}
statusRdr.Close();
completeView.DataSource = averageTable;
completeView.DataBind();

Need to add a hyperlinkfield to a gridview containing data from another column

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>

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