Gridview bound to datatable edit dropdownlist C# - c#

I have a GridView that is bound to a DataTable, and when you select edit, I can get the values to change. However, one field needs to be a dropdownlist and not a textbox. Here's the code I have so far.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
//dt.Rows[row.DataItemIndex]["Shipping Method"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
DropDownList cmbType = (DropDownList)griditems.Rows[e.RowIndex].FindControl("Shipping Method");
griditems.EditIndex = -1;
BindData();
}
}
When I uncomment the line for the shipping method to be a textbox, it does just as it says, a textbox, not a dropdownlist. I have tried changing it to a DropDownList with no luck.
In the aspx file:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing"
onrowupdating="griditems_RowUpdating" AllowPaging="True" onpageindexchanging="griditems_PageIndexChanging"
onrowcancelingedit="griditems_RowCancelingEdit" ViewStateMode="Enabled" Caption="Order Details"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
onrowdatabound="griditems_RowDataBound" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double" /></asp:GridView>
and when the table is generated:
public void CreateTable()
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}

Try dis:
Default.aspx: (Best practise use Template Field in GridView)
<asp:GridView ID="gvshipping" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="gvshipping_RowCancelingEdit"
onrowdatabound="gvshipping_RowDataBound"
onrowediting="gvshipping_RowEditing" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Part">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("part") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" Text='<%# Bind("part") %>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quatity">
<ItemTemplate>
<asp:Label ID="lblqty" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtqty" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship to">
<ItemTemplate>
<asp:Label ID="lblshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post date">
<ItemTemplate>
<asp:Label ID="lblpostdate" runat="server" Text='<%# Bind("RequestedDate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpostdate" Text='<%# Bind("RequestedDate")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate>
<asp:Label ID="lblshipmethod" runat="server" Text='<%# Bind("ShippingMethod")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvBind();
}
}
public void gvBind()
{
DataTable dt = createTable();
Session["tb"] = dt;
gvshipping.DataSource = Session["tb"];
gvshipping.DataBind();
}
protected void gvshipping_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dpshipmethod = (DropDownList)e.Row.FindControl("DropDownList1");
//bind dropdownlist
DataTable dt = shipingmethodTable();
dpshipmethod.DataSource = dt;
dpshipmethod.DataTextField = "ShippingMethod";
dpshipmethod.DataValueField = "Id";
dpshipmethod.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
dpshipmethod.SelectedItem.Text = dr["ShippingMethod"].ToString();
}
}
}
protected void gvshipping_RowEditing(object sender, GridViewEditEventArgs e)
{
gvshipping.EditIndex = e.NewEditIndex;
vBind();
}
protected void gvshipping_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvshipping.EditIndex = -1;
gvBind();
}
public DataTable createTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Part", typeof(string));
dt.Columns.Add("Quantity", typeof(Int32));
dt.Columns.Add("ShipTo", typeof(string));
dt.Columns.Add("RequestedDate", typeof(string));
dt.Columns.Add("ShippingMethod", typeof(string));
string date= DateTime.Now.ToShortDateString();
DataRow row = dt.NewRow();
row["Part"] = "Anchor";
row["Quantity"] = "10";
row["ShipTo"] = "blah";
row["RequestedDate"] = date;
row["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row);
DataRow row1 = dt.NewRow();
row1["Part"] = "blade";
row1["Quantity"] = "88";
row1["ShipTo"] = "blah";
row1["RequestedDate"] = date;
row1["ShippingMethod"] = "Charge by quantity";
dt.Rows.Add(row1);
DataRow row2 = dt.NewRow();
row2["Part"] = "cabin";
row2["Quantity"] = "4";
row2["ShipTo"] = "blah";
row2["RequestedDate"] = date;
row2["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row2);
DataRow row3 = dt.NewRow();
row3["Part"] = "cockpit";
row3["Quantity"] = "11";
row3["ShipTo"] = "blah";
row3["RequestedDate"] = date;
row3["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row3);
DataRow row4 = dt.NewRow();
row4["Part"] = "jack";
row4["Quantity"] = "45";
row4["ShipTo"] = "blah";
row4["RequestedDate"] = date;
row4["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row4);
DataRow row5 = dt.NewRow();
row5["Part"] = "cabin";
row5["Quantity"] = "67";
row5["ShipTo"] = "blah";
row5["RequestedDate"] = date;
row5["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row5);
DataRow row6 = dt.NewRow();
row6["Part"] = "blade";
row6["Quantity"] = "4";
row6["ShipTo"] = "blah";
row6["RequestedDate"] = date;
row6["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row6);
return dt;
}
public DataTable shipingmethodTable()
{
DataTable dtshipingmethod = new DataTable();
dtshipingmethod.Columns.Add("Id", typeof(Int32));
dtshipingmethod.Columns.Add("ShippingMethod", typeof(string));
DataRow row = dtshipingmethod.NewRow();
row["Id"] = 1;
row["ShippingMethod"] = "Charge by subtotal";
dtshipingmethod.Rows.Add(row);
DataRow row1 = dtshipingmethod.NewRow();
row1["Id"] = 2;
row1["ShippingMethod"] = "Charge by weight";
dtshipingmethod.Rows.Add(row1);
DataRow row2 = dtshipingmethod.NewRow();
row2["Id"] = 3;
row2["ShippingMethod"] = "Charge by quantity";
dtshipingmethod.Rows.Add(row2);
return dtshipingmethod;
}
ScreenShot:

you can go ahead with the help of this:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)row.FindControl("DropdownList1")).SelectedItem;
EDIT:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)
(row.Cells[5].Controls[0])).SelectedItem.ToString();

Related

asp.net Gridview does not display

I try to bind my list of objects to my datasource.
But as I switched from autogeneratecolums to boundfields, the whole grid is not displayed anymore.
Is there something I miss to let this work proper?
asp:
<asp:GridView ID="grid_article"
AutoGenerateColumns="false"
runat="server"
GridLines="None"
AllowPaging="true"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="ArticleGrid_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" ReadOnly="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="itemNumber" HeaderText="Product Number" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="name" HeaderText="Product Name" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Product Description" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="purchasePrice" HeaderText="Purchase Price" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="salesPrice" HeaderText="Sales Price" ReadOnly="true"></asp:BoundField>
</Columns>
</asp:GridView>
code behind:
if (articles != null)
{
if (articles.Count != 0)
{
DataTable dt = new DataTable();
dt.Columns.Add("itemNumber");
dt.Columns.Add("name");
dt.Columns.Add("description");
dt.Columns.Add("purchasePrice");
dt.Columns.Add("salesPrice");
foreach (AccessoryDTO item in articles)
{
DataRow dr = dt.NewRow();
dr["itemNumber"] = item.itemNumber;
dr["name"] = item.name;
dr["description"] = item.description;
dr["purchasePrice"] = item.purchasePrice + " " + item.currency;
dr["salesPrice"] = item.salesPrice + " " + item.currency;
dt.Rows.Add(dr);
}
grid_article.DataSource = dt;
show_record_count(articles.Count);
grid_article.DataBind();
}
else
{
grid_article.DataSource = null;
grid_article.DataBind();
}
}
try like this code that i worked with in sharepoint 2013 :
<asp:GridView ID="OffresGrid" CssClass="dataTable" runat="server" AutoGenerateColumns="false" EmptyDataText="Pas de données." AllowPaging="True" PageSize="1000" OnPageIndexChanging="OffresGrid_PageIndexChanging" OnRowDataBound="OffresGrid_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Secteur">
<ItemTemplate>
<asp:Label ID="Secteur" runat="server" Text='<%#Eval("Secteur") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Réference">
<ItemTemplate>
<asp:LinkButton ID="Reference" runat="server" Text='<%#Eval("Reference") %>' OnCommand="reference_Command" CommandArgument='<%#Eval("Reference") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Titre">
<ItemTemplate>
<asp:Label ID="Title" runat="server" Text='<%#Eval("Title")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date limité">
<ItemTemplate>
<asp:Label ID="DateLimite" runat="server" Text='<%#Eval("DateLimite")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date de publication">
<ItemTemplate>
<asp:Label ID="DatePublication" runat="server" Text='<%#Eval("DatePublication")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lieux">
<ItemTemplate>
<asp:Label ID="Lieux" runat="server" Text='<%#Eval("Lieux")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
C# code :
DataTable dt = new DataTable();
string Secteur, Reference, Title, DateLimite, DatePublication, Lieux;
dt.Columns.Add("Secteur", typeof(string));
dt.Columns.Add("Reference", typeof(string));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("DateLimite", typeof(string));
dt.Columns.Add("DatePublication", typeof(string));
dt.Columns.Add("Lieux", typeof(string));
try
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Offres"];
SPListItemCollection coll = list.Items;
foreach (SPListItem item in coll)
{
if (item["Secteur"] != null)
{
Secteur = item["Secteur"].ToString();
}
else
{
Secteur = "";
}
if (item["Reference"] != null)
Reference = item["Reference"].ToString();
else
Reference = " ";
if (item["Title"] != null)
Title = item["Title"].ToString();
else
Title = " ";
if (item["DateLimite"] != null)
DateLimite = item["DateLimite"].ToString();
else
DateLimite = " ";
if (item["DatePublication"] != null)
DatePublication = item["DatePublication"].ToString();
else
DatePublication = " ";
if (item["Lieux"] != null)
Lieux = item["Lieux"].ToString();
else
Lieux = " ";
dt.Rows.Add(Secteur, Reference, Title, DateLimite,
DatePublication, Lieux);
}
OffresGrid.DataSource = dt;
OffresGrid.DataBind();
}
}
}
catch (Exception )
{
}

How to group specific column in grid view

In Grid view I am having one field Items Group. I want to group all the Item group values together in gridview row wise with header name as Itemgroup.
Like Header Text as Itemgroup values followed by its values respectfully.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items Group">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("TestItemGroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:TextBox ID="txtItemGroup" runat="server" Text='<%# Eval("ItemGroup") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblGroup12" runat="server" Text='<%# Eval("TestItemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="lblItemValue" runat="server" Text='<%# Eval("TestItemValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default Values">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%# Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
int ID = Convert.ToInt32(txtID.Text);
sqlstr = "select * from Test_Items where TestID = '" + ID + "'";
SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
btnSend1.Visible = true;
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('Invalid ID (or) No Data to Display..!');", true);
}
For Better understanding Ex:
http://www.pathology-software.com/images/pathology-software/patholgy-screenshot7.jpg
Thank you in Advance
You can inject the needed separator rows by adding “separator records” to the data source before binding it to the GridView.
Here is an example I came across:
protected override void Render(HtmlTextWriter writer)
{
string lastSubCategory = String.Empty;
Table gridTable = (Table)gvProducts.Controls[0];
foreach (GridViewRow gvr in gvProducts.Rows)
{
HiddenField hfSubCategory = gvr.FindControl("hfSubCategory") as
HiddenField;
string currSubCategory = hfSubCategory.Value;
if (lastSubCategory.CompareTo(currSubCategory) != 0)
{
int rowIndex = gridTable.Rows.GetRowIndex(gvr);
// Add new group header row
GridViewRow headerRow = new GridViewRow(rowIndex, rowIndex,
DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell headerCell = new TableCell();
headerCell.ColumnSpan = gvProducts.Columns.Count;
headerCell.Text = string.Format("{0}:{1}", "SubCategory",
currSubCategory);
headerCell.CssClass = "GroupHeaderRowStyle";
// Add header Cell to header Row, and header Row to gridTable
headerRow.Cells.Add(headerCell);
gridTable.Controls.AddAt(rowIndex, headerRow);
// Update lastValue
lastSubCategory = currSubCategory;
}
}
base.Render(writer);
}
FULL ARTICLE
<asp:Literal ID="litDataLoader" runat="server">
</asp:Literal>
<asp:GridView ID="gvTemp" runat="server" AutoGenerateColumns="false" BorderWidth="0" ShowHeader="false" ShowFooter="false">
<Columns>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblTestItemName" runat="server" Text='<%#Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="220px">
<ItemTemplate>
<asp:Label ID="lblTestItemValues" runat="server" Text='<%#Eval("Itm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%#Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding Grid view in .cs:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void bindData()
{
string Query = "select TestItemID,TestItemName,TestItemValues,DefaultValues,TestID,ItemGroup,isnull(TestItemGroup,'-') as TestItemGroup, (ItemGroup + ' ' + TestItemValues) as Itm from Test_Items where TestID = '" + ViewState["id"].ToString() + "'";
SqlDataAdapter da = new SqlDataAdapter(Query, con);
DataTable dt = new DataTable();
da.Fill(dt);
var rows = dt.AsEnumerable().Select(s => new { id = s.Field<string>("TestItemGroup"), }).Distinct().ToList();
int count = rows.Count;
if (dt.Rows.Count > 0)
{
StringBuilder build = new StringBuilder();
foreach (var row in rows)
{
string Name = row.id != "-" ? row.id : " ";
build.Append("<b>" + Name + "</b>");
DataTable dts = new DataTable();
dts = dt.Select("TestItemGroup = '" + row.id + "'").CopyToDataTable();
gvTemp.Visible = true;
gvTemp.DataSource = dts;
gvTemp.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvTemp.RenderControl(hw);
string gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
build.Append(gridHTML);
gvTemp.Visible = false;
}
litDataLoader.Text = build.ToString();
}
}

asp.net gridview Sorting by date

I am sorting my date with my sql query and I get a proper result.
But as I apply
gridview.UseAccessibleHeader = true;
gridview.HeaderRow.TableSection = TableRowSection.TableHeader;
to my gridview. The sorted data gets unsorted.
this.gridviewname.MasterTemplate.EnableSorting = true;
this.RadGridView1.MasterTemplate.EnableSorting = True
SortDescriptor descriptor = new SortDescriptor();
descriptor.PropertyName = "Yourcolumnname";
descriptor.Direction = ListSortDirection.Ascending;
this.gridviewname.MasterTemplate.SortDescriptors.Add(descriptor);
descriptorcolumnname As New SortDescriptor()
descriptorShipName.PropertyName = "columnname"
descriptorShipName.Direction = ListSortDirection.Ascending
try this
Try this code which is working fine for me.
-- C# Code here---
<form id="form1" runat="server">
<div>
<h1>Gridview Property of Sorting</h1>
<br />
<asp:GridView ID="gdviewevent" runat="server" AutoGenerateColumns="false" OnSorting="gdviewevent_Sorting" AllowSorting="true">
<HeaderStyle BackColor="YellowGreen" Font-Bold="True" Font-Names="cambria" ForeColor="Black" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:TemplateField HeaderText="Sr No.">
<ItemTemplate>
<span><%#Container.DataItemIndex+1 %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="India Value" SortExpression="IndiaVal">
<ItemTemplate>
<asp:Label ID="lblindiavalue" runat="server" Text='<%#Eval("Column1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date" SortExpression="Registereddate">
<ItemTemplate>
<asp:Label id="lblcreateddate" runat="server" Text='<%#Eval("Registereddate", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
-- Page behind Code ---
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridView();
}
}
protected void FillGridView()
{
string query = "Select Column1, Registereddate from tablename";
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gdviewevent.DataSource = dt;
gdviewevent.DataBind();
ViewState["dirState"] = dt;
ViewState["sortdr"] = "Asc";
}
}
protected void gdviewevent_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
gdviewevent.DataSource = dtrslt;
gdviewevent.DataBind();
}
}

Importing data from csv to GridView ASP.NET/C#

I am trying to import data from a csv to a gridview, but for some reason, I get the following error:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Col5'.
Here is how the csv looks like:
I would like to display in the GridView in this same format, and set the column names and row names to "Q1, "Q2", "Q3", "Q4", "Q5".
Could anyone please help? Thank you in advance. P.S: I am a beginner at ASP.NET
Here is my code:
aspx
<asp:GridView ID="TurnoverGridView" runat="server" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False"
Width="318px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True">
<AlternatingRowStyle BackColor="White" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemStyle Font-Size="13px" Width="10%" />
<ItemTemplate>
<asp:Label ID="RowLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col1") %>'
Style="text-align: left; font-weight:bold"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q1">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FirstLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col2") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q2">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="SecondLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col3") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q3">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="ThirdLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col4") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q4">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FourthLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col5") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q5">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FifthLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col6") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string dir = #"Directory"; // Directory where the file exists
string turnover_fi = dir + "\\turnover_ac_bull.csv";
FirstTurnoverGridViewRow();
DataTable dt = (DataTable)Session["currentTurnoverTable"];
//DataTable dt = new DataTable();
dt = (DataTable)ReadToEnd(turnover_fi);
if (dt != null && dt.Rows.Count > 0)
{
TurnoverGridView.DataSource = dt;
TurnoverGridView.DataBind();
}
}
}
private object ReadToEnd(string filePath)
{
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(filePath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count() - 1; i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}
for (int i = 0; i < fileContent.Count(); i++)
{
string[] row = fileContent[i].Split(',').Take(fileContent[i].Split(',').Length - 1).ToArray();
DataRow dr = dtDataSource.NewRow();
for (int j = 0; j < row.Length; j++)
{
dr[j] = row[j];
}
dtDataSource.Rows.Add(dr);
}
}
return dtDataSource;
}
protected void FirstTurnoverGridViewRow()
{
DataTable table = new DataTable();
string[] row_names = new string[] { "Q1", "Q2", "Q3", "Q4", "Q5" };
table.Columns.Add(new DataColumn("Col1", typeof(string)));
table.Columns.Add(new DataColumn("Col2", typeof(double)));
table.Columns.Add(new DataColumn("Col3", typeof(double)));
table.Columns.Add(new DataColumn("Col4", typeof(double)));
table.Columns.Add(new DataColumn("Col5", typeof(double)));
table.Columns.Add(new DataColumn("Col6", typeof(double)));
DataRow dr = table.NewRow();
for (int i = 0; i < row_names.Count(); i++)
{
dr = table.NewRow();
string text = row_names[i];
dr["Col1"] = row_names[i];
dr["Col2"] = DBNull.Value;
dr["Col3"] = DBNull.Value;
dr["Col4"] = DBNull.Value;
dr["Col5"] = DBNull.Value;
dr["Col6"] = DBNull.Value;
table.Rows.Add(dr);
}
ViewState["currentTurnoverTable"] = table;
TurnoverGridView.Visible = true;
TurnoverGridView.DataSource = table;
TurnoverGridView.DataBind();
}
the for loop inside ReadToEnd(string filePath) function
for (int i = 0; i < columns.Count() - 1; i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}
it should read as
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}

set values to TextBox in Item template of gridview

I'm working with Outward Challan Detail, in which I need to show the results on a form by a gridview.
My problem is that I don't know how to assign values to textbox existing in the gridview.
How could I assign values in the textbox inside my templates fields that are in my gridview by using dataReader or DataSet?
Here is my aspx
<div id="OutDCItemDetails" runat="server" style="overflow:auto">
<asp:Panel ID="PanelOutDCItemDetails" runat="server">
<asp:GridView ID="gvOutDCItemDetails" runat="server" AllowPaging="True"
PageSize="6" AutoGenerateColumns="False"
onrowdatabound="gvOutDCItemDetails_RowDataBound"
onrowcommand="gvOutDCItemDetails_RowCommand"
onselectedindexchanged="gvOutDCItemDetails_SelectedIndexChanged"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3" CellSpacing="1" GridLines="None" DataKeyNames="Item_Id" >
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField HeaderText="Item Id" DataField="Item_Id" />
<asp:BoundField HeaderText="Item Name" DataField="IName" />
<asp:BoundField HeaderText="Net Quantity" DataField="I_Quantity" />
<asp:BoundField DataField="Remaining_Qty" HeaderText="Remaining Quantity" />
<asp:TemplateField HeaderText="Process">
<ItemTemplate>
<asp:DropDownList ID="ddrProcess" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dispatch Quantity">
<ItemTemplate>
<asp:TextBox ID="txtDispatchQuantity" runat="server" AutoPostBack="true" OnTextChanged="TextChanged_txtDispatchQuantity"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remaining Quantity">
<ItemTemplate>
<asp:TextBox ID="txtRamainingQuantity" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="txtRate" runat="server" AutoPostBack="true" OnTextChanged="txtRate_TextChanged"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text="Status"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
Here is my C# code
protected void gvOutDC_SelectedIndexChanged1(object sender, EventArgs e)
{
if (gvOutDC.SelectedIndex >= 0)
{
btnsave.Enabled = false;
btnInword.Visible = false;
OutDC.Visible = true;
OutDCItemDetails.Visible = true;
View.Visible = false;
InwordDetails.Visible = false;
txtOutId.Visible = true;
txtoutCode.Enabled = false;
btn.Visible = true;
txtcustcode.Enabled = false;
btnsave.Enabled = true;
txtOutId.Text = gvOutDC.SelectedDataKey[0].ToString();
txtoutCode.Text = gvOutDC.SelectedRow.Cells[2].Text.ToString();
txtDate.Text =gvOutDC.SelectedRow.Cells[8].Text.ToString();
txtCustomerId.Text = gvOutDC.SelectedRow.Cells[5].Text.ToString();
txtcustcode.Text = gvOutDC.SelectedRow.Cells[7].Text.ToString();
txtCustomerName.Text = gvOutDC.SelectedRow.Cells[6].Text.ToString();
int inworditem = Convert.ToInt16(gvOutDC.SelectedRow.Cells[3].Text.ToString());
SqlCommand cmd = new SqlCommand("sp_getOutDCmaterialDetail",con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#outDCid", txtOutId.Text);
cmd.Parameters.AddWithValue("#inwordItem", inworditem);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
//.Text = ds.Tables[0].Rows[0][0].ToString();
con1.Open();
//SqlDataReader dr=cmd.ExecuteReader();
//if (dr.HasRows)
//{
// while (dr.Read())
// {
// }
//}
gvOutDCItemDetails.DataSource = ds;
gvOutDCItemDetails.DataBind();
OutDCItemDetails.Visible = true;
}
}
protected void gvOutDCItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if ((e.Row.RowState & DataControlRowState.Edit) > 0)
//{
DropDownList ddList = (DropDownList)e.Row.FindControl("ddrProcess");
//bind dropdownlist
SqlCommand cmd = new SqlCommand("sp_getProcess", con1);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
//DataTable dt = con1.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "PName";
ddList.DataValueField = "Process_Id";
ddList.DataBind();
ddList.Items.Insert(0,new ListItem("--SELECT--","0"));
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
txtDispatchQuantity.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtRamainingQuantity = (TextBox)e.Row.FindControl("txtRamainingQuantity");
txtRamainingQuantity.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtRate = (TextBox)e.Row.FindControl("txtRate");
txtRate.Text = ds.Tables[0].Rows[0][3].ToString();
TextBox txtAmount = (TextBox)e.Row.FindControl("txtAmount");
txtAmount.Text = ds.Tables[0].Rows[0][3].ToString();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
// Label lblTotalPrice = (Label)e.Row.FindControl("Total_Amount");
//lblTotalPrice.Text = total.ToString();
// txttotalAmount.Text = Total.ToString();
}
}
You should directly bind the DataTable Column to TextBox inside the TemplateField like...
<asp:TextBox ID="txtDispatchQuantity" runat="server" Text='<%# Eval("ColumnNameInDataSetTable") %>' />
This directly binds the values to TextBoxes. You can do this for all other TextBoxes.
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
var dataRow = (DataRowView)e.Row.DataItem;
var Dispatch_Qty = "Dispatch_Qty";
var check = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(Dispatch_Qty, StringComparison.InvariantCultureIgnoreCase));
if (check)
{
// Property available
txtDispatchQuantity.Text =ds1.Tables[0].Rows[0][7].ToString();
}
protected void gvOutDCItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if ((e.Row.RowState & DataControlRowState.Edit) > 0)
//{
DropDownList ddList = (DropDownList)e.Row.FindControl("ddrProcess");
//bind dropdownlist
SqlCommand cmd = new SqlCommand("sp_getProcess", con1);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
//DataTable dt = con1.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "PName";
ddList.DataValueField = "Process_Id";
ddList.DataBind();
ddList.Items.Insert(0,new ListItem("--SELECT--","0"));
TextBox txtDispatchQuantity = (TextBox)e.Row.FindControl("txtDispatchQuantity");
var dataRow = (DataRowView)e.Row.DataItem;
var Dispatch_Qty = "Dispatch_Qty";
var check = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(Dispatch_Qty, StringComparison.InvariantCultureIgnoreCase));
if (check)
{
// Property available
txtDispatchQuantity.Text =ds1.Tables[0].Rows[0][7].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
// Label lblTotalPrice = (Label)e.Row.FindControl("Total_Amount");
//lblTotalPrice.Text = total.ToString();
// txttotalAmount.Text = Total.ToString();
}
}
A short way with Simple and Inner Select, For use in ASPX code with no Code Behind:
....
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("COrder") %>' />
</td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("CText") %>' />
</td>
<td>
Delete
</td>
</tr>
</ItemTemplate>
....
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [RId],[CId],[COrder],[CText]=(SELECT [Title] from [Categories] where [ID]=[HomeProduct].[CId]) FROM [HomeProduct] ORDER BY [COrder] DESC"></asp:SqlDataSource>

Categories

Resources