Importing data from csv to GridView ASP.NET/C# - 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));
}

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 can I add a row above the BoundField in ASP.NET GridView [duplicate]

This question already has answers here:
How to add Header and Subheader in Gridview
(2 answers)
Closed 7 years ago.
I want to add a row above the BoundField. This is my GridView:
<asp:GridView ID="grdvProductChurn" runat="server" CellPadding="4" HeaderStyle-BorderStyle="None"
BorderColor="#666666" BorderStyle="Solid" AllowPaging="True" AutoGenerateColumns="false" PageSize="30" DataSourceID="DataSource_ProductChurn"
AllowSorting="True" ForeColor="#666666" CellSpacing="1" DataFormatString="{0:###,###,###,###,###}"
CaptionAlign="Left" Width="960px" HeaderStyle-HorizontalAlign="Center" HorizontalAlign="Center" CssClass="GridView2"
Height="119px" >
<Columns>
<asp:BoundField ReadOnly="true" DataField="Produktgruppe" HeaderText="Produktgruppe" SortExpression="Produktgruppe" HeaderStyle-HorizontalAlign="Left" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Produkt" HeaderText="Produkt" SortExpression="Produkt" HeaderStyle-HorizontalAlign="Left" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_Jan" HeaderText="Jan" SortExpression="Anzahl_Jan" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_Feb" HeaderText="Feb" SortExpression="Anzahl_Feb" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_Mar" HeaderText="Mar" SortExpression="Anzahl_Mar" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_Apr" HeaderText="Apr" SortExpression="Anzahl_Apr" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_May" HeaderText="May" SortExpression="Anzahl_May" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField ReadOnly="true" DataField="Anzahl_Jun" HeaderText="Jun" SortExpression="Anzahl_Jun" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:###,###,###,###,###,0}" >
<ControlStyle Font-Bold="False" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" ForeColor="#666666" />
<PagerSettings Mode="Numeric" />
<PagerStyle ForeColor="#11AAFF" Font-Names='"Trebuchet MS", Arial, Sans' Font-Size="12px" HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" VerticalAlign="Top" />
<SelectedRowStyle HorizontalAlign="Left"></SelectedRowStyle>
</asp:GridView>
At the moment it looks like that, but now I want to add a row above:
It should look like that, how can I add a row above the BoundField HeaderText?
I would like to do it right in the aspx file if it's even possible.
I made a method inside the codebehind.
This is my code now and it works.
protected void grdvProductChurn_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);
HeaderCell = new TableCell();
HeaderCell.Text = "Anzahl";
HeaderCell.ColumnSpan = 6;
HeaderGridRow.Cells.Add(HeaderCell);
grdvProductChurn.Controls[0].Controls.AddAt(0, HeaderGridRow);
}
}
You can try it with this example :
protected void HeaderTest(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Test";
HeaderCell.ColumnSpan = 6;
HeaderGridRow.Cells.Add(HeaderCell);
HeaderCell = new TableCell();
HeaderCell.Text = "Test1";
HeaderCell.ColumnSpan = 4;
HeaderGridRow.Cells.Add(HeaderCell);
grdvProductChurn.Controls[0].Controls.AddAt(0, HeaderGridRow);
}
}
From : How to add Header and Subheader in Gridview
You can add it like following-
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Produktgruppe", typeof(string));
dt.Columns.Add("Produkt", typeof(string));
dt.Columns.Add("Jan", typeof(string));
dt.Columns.Add("Feb", typeof(string));
dt.Columns.Add("March", typeof(string));
dt.Columns.Add("may", typeof(string));
dt.Columns.Add("Jun", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = " ";
NewRow[1] = "Anzahl";
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
I hope this can help you.

loading vertical columns in grid with data's coming from database

I wanted to load the grid columns vertically with data's coming from database.Please someone help me.I wanted to further edit in the gridcolumn. below is my code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="95%" style="text-align:center;" GridLines="Both"
AutoGenerateColumns="false" DataKeyNames="WORKSHEET_ID" HeaderStyle-ForeColor="White" onrowediting="EditTaskStatus" onrowupdating="UpdateTaskStatus" onrowcancelingedit="CancelTaskStatus"
AllowPaging ="true" emptydatatext="No Approval Task" OnPageIndexChanging = "OnPaging" BackColor="AliceBlue" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F2F2F2" RowStyle-BorderWidth="1" AlternatingRowStyle-BorderWidth="1"
HeaderStyle-BackColor = "#00829c" HeaderStyle-BorderColor="#CC9966" PagerStyle-CssClass="pagenation" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderStyle="Solid" EditRowStyle-Wrap="true"
PageSize = "5">
<Columns>
<asp:TemplateField Visible="false" ItemStyle-Width = "30px" HeaderText = "Id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server"
Text='<%# Eval("WORKSHEET_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "50px" HeaderText ="Total Hours">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"
Text='<%# Eval("TOTAL_HOURS")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Final Status" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:Label ID="lblFinalStatus" runat="server" Text='<%# Eval("MGR_STATUS") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlTaskStatus">
<asp:ListItem Text="Accept" Value="1"></asp:ListItem>
<asp:ListItem Text="Decline" Value="2"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText ="Comments">
<EditItemTemplate>
<asp:TextBox ID="txtComments" runat="server"
Text='<%# Eval("MGR_COMMENTS") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width = "50px">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/images/edit.gif" Width="16" Height="16" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/images/action_check.gif" Width="16" Height="16" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/images/action_delete.gif" Width="16" Height="16" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help me in the backend i have given the code as
protected void BindGridviewData()
{
DataTable dt = new DataTable();
string strQuery = "SELECT * from Master_Worksheets where MGR_CODE ='" + lblUsername.Text + "' AND (MGR_STATUS='New' OR MGR_STATUS='Decline')";
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
gvconverted.DataSource = ConvertColumnsAsRows(dt);
gvconverted.DataBind();
gvconverted.HeaderRow.Visible = false;
}
public DataTable ConvertColumnsAsRows(DataTable dt)
{
DataTable dtnew = new DataTable();
//Convert all the rows to columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
dtnew.Columns.Add(Convert.ToString(i));
}
DataRow dr;
// Convert All the Columns to Rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = dtnew.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
dr[k] = dt.Rows[k - 1][j];
dtnew.Rows.Add(dr);
}
return dtnew;
}
I guess you need to swap the rows and columns of Datatable.
If that is what you need then please refer this link. It will help you
http://www.codeproject.com/Articles/44274/Transpose-a-DataTable-using-C

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>

Gridview bound to datatable edit dropdownlist 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();

Categories

Resources