Issue with binding datatable to gridview - c#

I am calling the server and returning a datatable of results but when I try to bind to the gridview, it is throwing an error about not being able to find a field or property on the data source. I'm newer to gridviews and .NET controls so any help would be appreciated.
The GridView
<asp:GridView ID="gv_Search" AutoGenerateColumns="false" runat="server" AllowSorting="true" OnSorting="gv_Search_Sorting">
<Columns>
<asp:HyperLinkField NavigateUrl="#" Text="View"/>
<asp:BoundField SortExpression="Hdefendant_name" HeaderText="Name" DataField="Hdefendant_name"/>
<asp:BoundField SortExpression="Hdefendant_location" HeaderText="Location" DataField="Hdefendant_location"/>
<asp:BoundField SortExpression="Hdate" HeaderText="Date Entered" DataField="Hdate"/>
</Columns>
</asp:GridView>
The Code-Behind for Gridview page
(resultsList is a DataTable type)
var resultsList = defendantRepository.Search(start, end, name, location);
if (Defendant.hasRecords)
{
ViewState["PreliminaryInjunctions"] = resultsList.Columns;
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
}
The Search (populates a DataTable and returns it to the variable resultsList from above)
dv is a DefaultView and
ds is a DataSet
using (var da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(ds, "PreliminaryInjunctions");
}
dv = ds.Tables[0].DefaultView;
dt = dv.ToTable();
return dt;

The issue is I believe that you are binding the GridView to the Data Table's Columns property:
gv_Search.DataSource = resultsList.Columns;
gv_Search.DataBind();
That property is of type DataColumnCollection which does not contain names matching those defined in the BoundField elements, and hence the error.
Instead bind to the DataTable itself:
gv_Search.DataSource = resultsList;
gv_Search.DataBind();

Related

Bind Links To GridView

How can I render links in columns of WebForms GridView?
I have the following code
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.UsersContacts WHERE UserId='vika'", con);
con.Open();
var list1 = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var node = reader[1];
list1.Add(node.ToString());
}
}
con.Close();
GridView1.DataSource = list1;
GridView1.DataBind();
and I want to do something such as list1.Add("<a href='#'>"+node.ToString()+"<a>"); and make it a link in my GridView.
I would rather do this at the gridview template definition instead of passing the link from the datasource. Your gridview definition can have the asp:HyperLinkField or asp:HyperLink field and bind the data as required.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperLinkField
HeaderText="View Details"
DataNavigateUrlFields="node"
DataNavigateUrlFormatString="~/TargetPage.aspx?Id={0}"
DataTextField="node"
/>
</Columns>
</asp:GridView>
Or
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("node", "~/TargetPage.aspx?Id={0}") %>' Text="View Details" />

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

Search query returns none

I have a stored procedure in SQL that searches employee details. When it finds something,it returns and displays the data in a gridview. But how can I handle if it did not return anything? like when 'no record is found'?
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("[Reader].[usp_SearchUser]", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#empID", SqlDbType.Int).Value = this.EmpID;
con.Open();
int result = com.ExecuteNonQuery();
if (result == 0)
{
this.NoRecord = "No Record Found";
}
else
{
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
search.DataSource = ds;
search.DataBind();
}
}
}
Did not get what is your exact question? do you want the gridview property when there is no data then it will show as no records found i.e. EmptyDataText="No records Found"
e.g.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No records Found">
<Columns>
<asp:boundfield datafield="empID" headertext="Employee ID"/>
<asp:boundfield datafield="empName" headertext="Employee Name"/>
</Columns>
</asp:GridView>
I suppose you use a webcontrol GridView? So you might use the GridView.EmptyDataTemplate to have full control of what to render if no data has been bound.
<asp:gridview id="yourGridView" runat="server">
<emptydatatemplate>
No Data Found!
<img src="noData.jpg"/>
</emptydatatemplate>
</asp:gridview>
Or just use EmptyDataText Property if you just want to show a text Message
<asp:gridview id="yourGridView" emptydatatext="No Data Found" runat="server">
....
</asp:gridview>

How to change the order of columns in GridView using Asp.Net C#

I have a grid which is being bound in code behind in which i want to display template field also.
I am generating 3 columns in DataTable for grid view and the template field is TextBox control.
My code for binding data is..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class gr4 : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");
string query = "Select Capacity from Dealer_License_Capacity where ID='D00001' and Software_ID='001' and Version_ID='1'";
cn.Open();
cmd = new SqlCommand(query,cn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Software_Name", typeof(string));
dt.Columns.Add("Version_Name", typeof(string));
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
for (int i = 0; i < count; i++)
{
DataRow dr = dt.NewRow();
dr["Name"] = "aaa";
dr["Software_Name"] = "bbb";
dr["Version_Name"] = "ccc";
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
My source code for grid view is:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
The grid display template field as first column but I want to display the template field as last column in output. Can I add more template fields in this grid..??
Please help..
Thanks in advance
You can use bound fields like below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" > /*changed to false*/
<Columns>
<asp:BoundField HeaderText="Name"
DataField="Name"/>
<asp:BoundField HeaderText="SoftwareName"
DataField="Software_Name"/>
<asp:BoundField HeaderText="VersionName"
DataField="Version_Name"/>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change the order as you like.
if all ready data is there in database and column is there at the same way in grid-view column name is name there has to display name is order how me not getting
my grid code is this one but not coming order wise

DataBinding DataSet to GridView yields infinite loop

I am attempting to bind a GridView to a DataSet, but it throws a Stack overflow error. When I debug it, it runs to the DataBind line just fine (it seems like its getting the right records from the server and everything), but after executing the DataBind, it jumps to the top of the method and reruns the entire method, which results in an stack overflow.
I can't understand why this isn't working. I've done something very similar with a DataTable before and it worked fine.
Here is how I'm binding
public void CreateGrid(String str)
{
try
{
sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MY_CONNECTION_STRING"].ConnectionString;
sqlConnection.Open();
DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(str, sqlConnection);
adapter.Fill(dt);
sqlConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
}
if (dt.Tables.Count > 0)
{
Grid.DataSource = dt;
Grid.DataBind();
}
}
And here is my HTML part
<asp:GridView runat="server" ID="Grid" AutoGenerateColumns="false"
OnDataBinding="RebindGrid" AllowPaging="True" PageSize="10" AllowSorting="True" CellPadding="5"
OnPageIndexChanging="Grid_PageIndexChanging"
OnSorting="Grid_Sorting"
Width="100%" CssClass="mGrid">
<Columns>
<asp:BoundField DataField="ID" ItemStyle-Width="0%"
HeaderText="" Visible="false" SortExpression="ID"/>
</Columns>
</asp:GridView>
This looks like a problem
OnDataBinding="RebindGrid"
Every time data is bound, you rebind. We would have to see the code for RebindGrid.
It depends on what the RebindGrid method actually does but it looks like your rebinding your grid as your binding it.
Remove OnDataBinding="RebindGrid".

Categories