delete a row from the gridview from .cs - c#

This is my aspx page
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None"
>
<Columns>
<asp:TemplateField HeaderText = "S.No">
<ItemTemplate>
<asp:Label ID="Sno" runat="server" Text= '<%#Eval("id")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Name">
<ItemTemplate >
<a href= "<%# Eval("Photo") %>" > <%# Eval("name") %> </a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Photo">
<ItemTemplate>
<img src='<%# Eval("Photo") %>' alt='<%# Eval("Name") %>' height= "50px" width = "50px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle 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" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
and this is my .cs file
public partial class people_db_mysql : System.Web.UI.Page
{
String MyConString = "SERVER=localhost;" +
"DATABASE=shortandsweet;" +
"UID=root;" +
"PASSWORD=;";
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(MyConString);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM people_details;", conn);
conn.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridViews1.DataSource = dataTable;
GridViews1.DataBind();
}}
now the output i get is
[ S.NO, Name , Photo , sno, name and photo ]
the first three fields are from the aspx page which i want it to be displayed and i dont want the other 3 fields to be displayed any ideas how i might achieve that ?
and moreover ive tried this
GridViews1.Columns[3or4or5].Visible = false; //and it says array out of bounds
however i can hide the 0,1,2 fields with the same command, is there a way to hide the rows generated through the .cs files ?
if i try to limit the rows through the select query it doesnt display anything, i just get a blank screen.

The Gridview control has a property 'AutoGenerateColumns' which has to be set to 'false', otherwise it will autogenerate the columns, even if you have manually added them.
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="false"
>

Related

Send Selected Rows In Gridview to Email

I'd like to send gridview rows to an email on button press. The number of rows selected vary and use check boxes.
Background:
The app consists of 2 GridViews. One acts as a schedule, the other acts as a holding area for items taken out of the schedule. Included below is what I use to move Items out of the schedule. The code to put items back into schedule is identical, so it was not included.
The email function is to notify the user what specific items were taken out/put into schedule.
GridView1
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" ShowHeaderWhenEmpty="True" BackColor="White" BorderColor="#003399" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnPageIndexChanging="GridView1_PageIndexChanging" Width="450px">
<Columns>
<asp:BoundField DataField="VEH_SER_NO" SortExpression="VEH_SER_NO" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" Width="75px" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="DATE_BLD_RATE" SortExpression="DATE_BLD_RATE" ReadOnly="True" DataFormatString="{0:yyyy/MM/dd}">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SEQ" SortExpression="SEQ" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SV_TYPE_CD" SortExpression="SV_TYPE_CD" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="COMMENT" SortExpression="COMMENT" Visible="False" ReadOnly="False" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#99CCCC" ForeColor="White" HorizontalAlign="center" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
Code:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
if (drpReason0.SelectedValue != "" && drpReason.SelectedValue != "")
{
string strSQL = "SELECT VEH_SER_NO, DATE_BLD_RATE, SEQ, SV_TYPE_CD, COMMENT FROM Schedule " +
"WHERE Schedule.id = #ID";
MoveRows(GridView1, strSQL);
}
}
void MoveRows(GridView gv, string strSQL)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
}
}
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(cs))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}

Still have problems with gridview and update for my database project

I want to Update An Number of goals That a Player Scored so if he socred a goal I want to do an update for his number of goals...
I got an Error in my Code And I don't know how to fix it. Can anyone help me to fix it, please ?
My Code:
string connectionStr = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\SoccerDataBase.mdb";
using (OleDbConnection sqlCon = new OleDbConnection(connectionStr))
{
sqlCon.Open();
string queryStr = "SELECT Achievement FROM SoccerAchievements WHERE UserID=#AchNums";
OleDbCommand sqlCmd = new OleDbCommand(queryStr, sqlCon);
sqlCmd.Parameters.AddWithValue("#AchNums", (SoccerTable.FooterRow.FindControl("AchNums") as TextBox).Text.Trim());
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
DataSet ds = new DataSet();
dataAdapt.Fill(ds, "SoccerAchievement");
DataRow row = ds.Tables["SoccerAchievement"].Rows[0];
int a = int.Parse(row[3].ToString());
a = a + int.Parse("#AchNums");
string query = "UPDATE SoccerAchievements SET Achievement= '" + a + "' WHERE UserID= #AchNums";
sqlCmd.ExecuteNonQuery();
}
My GridView HTML CODE:
<asp:GridView ID="SoccerTable" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="קוד שחקן" InsertVisible="False"
SortExpression="ID" />
<asp:BoundField DataField="Team" HeaderText="קבוצות" SortExpression="Team" />
<asp:BoundField DataField="Players" HeaderText="שחקנים"
SortExpression="Players" />
<asp:TemplateField HeaderText="הישגים">
<FooterTemplate>
<asp:TextBox ID="AchNums" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button class = "AddButton" ID="AddButton" runat="server" onclick="AddButton_Click" Text="עדכן" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
My Error: There is no row at position 0.
Image:
My Data SoccerAchievements
Image:
Please help me guys :)
Replace this
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
With
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(sqlCmd);
However you may again face error at your int.parse code.please correct that as well.

Retrieving data from DetailsView

I'm trying to retrieve data from the DetailsView control in order to input them into another database table. I've looked through other questions that others asked but none of their questions could fit into my situation, which is trying to access SQL Database. Ultimately, I couldn't find the answer I require.
Basically, my objective of the codes is to extract the second row of the DetailsView, since the first row are mostly the static headers that do not change. My DetailsView would change upon the selection of a GridView above. Hence, I'm trying to retrieve the data on the second row, explaining my usage of Rows[2] , while I presume that "Cells[]" refers to the columns.
I'm using the following codes to do so.
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con)
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
I've been thrown the following exception:
Error:System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index at System.Web.UI.ControlCollection.get_Item(Int32 index) at RealClientPurchase.Button1_Click(Object sender, EventArgs e) in d:\Desktop\RealClientPurchase.aspx.cs:line 27
EDIT:
This is the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class RealClientPurchase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
clientnolbl.Text = Session["sClientNo"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30");
try
{
con.Open();
SqlCommand cmd;
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"alert('Purchase order has been submitted! Kindly proceed to checkout.'); window.location='" +
Request.ApplicationPath + "CurrentCheckout.aspx';", true);
con.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}
These are the aspx codes:
<%# Page Title="" Language="C#" MasterPageFile="~/ClientPortal.master" AutoEventWireup="true" CodeFile="RealClientPurchase.aspx.cs" Inherits="RealClientPurchase" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDate] FROM [Quotations] WHERE ([qClientNo] = #qClientNo)">
<SelectParameters>
<asp:SessionParameter Name="qClientNo" SessionField="sClientNo" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDescription], [qPricePerQty], [qTotalPayable] FROM [Quotations] WHERE ([qQuotationNo] = #qQuotationNo)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="qQuotationNo" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="clientnolbl" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="qQuotationNo" DataSourceID="SqlDataSource1" Height="125px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="qQuotationNo" HeaderText="Quotation No" InsertVisible="False" ReadOnly="True" SortExpression="qQuotationNo" />
<asp:BoundField DataField="qServices" HeaderText="Services" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="Quantity" SortExpression="qQuantity" />
<asp:BoundField DataField="qDate" HeaderText="Date" SortExpression="qDate" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="50px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="qQuotationNo">
<AlternatingRowStyle BackColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<EditRowStyle BackColor="#2461BF" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="qQuotationNo" HeaderText="qQuotationNo" SortExpression="qQuotationNo" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="qServices" HeaderText="qServices" ReadOnly="True" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="qQuantity" SortExpression="qQuantity" ReadOnly="True" />
<asp:BoundField DataField="qDescription" HeaderText="qDescription" SortExpression="qDescription" ReadOnly="True" />
<asp:BoundField DataField="qPricePerQty" HeaderText="qPricePerQty" SortExpression="qPricePerQty" ReadOnly="True" />
<asp:BoundField DataField="qTotalPayable" HeaderText="qTotalPayable" SortExpression="qTotalPayable" ReadOnly="True" />
</Fields>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
</asp:DetailsView>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<br />
<br />
</asp:Content>
I've found the solution.
I changed the fields in the database table to exclude "#" and "[" or "]"
It appears these signs do not function well in a SQL statement.
Revamped codes are as follows, and they do work.
SqlCommand cmd;
string insertQuery = "INSERT INTO SalesOrders (pQuotationNo, pServices, pQty, pDescription, pPricePerQty, pNetvalue, pProgress, pClientNo) values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
cmd.ExecuteNonQuery();
Can you try DetailsView1.Rows[0].Cells[0].Text?
Since your DetailsView has BoundFields only, this should work.
Regards

dynamically set width of a column in Gridview

I am trying to dynamically set width of gridview columns but when I apply the following code, I see no change in the browser.
.aspx code is:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" CellSpacing="4" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CellPadding="4" DataKeyNames="File_Name" GridLines="None" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdated="GridView1_RowUpdated" OnRowUpdating="GridView1_RowUpdating" ForeColor="#333333" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnPageIndexChanging="GridView1_PageIndexChanging" AllowSorting="True" OnSorting="GridView1_Sorting" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_OnRowDataBound">
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="10" Position="Bottom" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnFileName" runat="server" CommandArgument='<%# Eval("File_Name") %>' CommandName="Download" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
.cs code is:
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//SET WIDTH OF THE COLUMNS
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = 100; //DATE
e.Row.Cells[1].Width = 100; //CUSTOMER
e.Row.Cells[2].Width = 100; //DESTINATION
}
}
Can anyone notice where I might be going wrong?
Please check .. I think you may need to do the following way
e.Row.Cells[0].Width = Unit.Pixel(500);
e.Row.Cells[1].Width = Unit.Pixel(500);

Displaying GridView at Page Load

I would like to manually add rows to a GridView, and display it at Page Load. For some reason, my current code shows an empty GridView.
Default.aspx
<asp:GridView ID="AllocationGridView" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="False"
Width="691px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True"
AutoPostBack="true">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="Asset Class">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:Label ID="AssetLabel" runat="server" ReadOnly="true" Text="" BorderWidth="0px"
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:TextBox ID="WeightTextBox" runat="server" ReadOnly="true" BorderWidth="0px"
Style="text-align: left;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle 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>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FirstAllocationGridViewRow();
}
}
protected void FirstAllocationGridViewRow()
{
DataTable table = new DataTable();
string[] assets = new string[] { "Cash", "US Equity", "Fixed Income", "BAS", "International" };
table.Columns.Add(new DataColumn("Col1", typeof(string)));
table.Columns.Add(new DataColumn("Col2", typeof(double)));
DataRow dr = table.NewRow();
for (int i = 0; i < assets.Count(); i++)
{
dr = table.NewRow();
dr["Col1"] = assets[i];
dr["Col2"] = DBNull.Value;
table.Rows.Add(dr);
}
ViewState["currentAllocationTable"] = table;
AllocationGridView.Visible = true;
AllocationGridView.DataSource = table;
AllocationGridView.DataBind();
}
your cs code is fine the problem is in your layout code. text property is not bind to table field name
Text='<%# Bind("Col1") %>'
here is the complete gridview
<asp:GridView ID="AllocationGridView" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="False"
Width="691px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True"
AutoPostBack="true">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="Asset Class">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:Label ID="AssetLabel" runat="server" ReadOnly="true" Text='<%# Bind("Col1") %>' BorderWidth="0px"
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:TextBox ID="WeightTextBox" runat="server" Text='<%# Bind("Col2") %>' ReadOnly="true" BorderWidth="0px"
Style="text-align: left;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle 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>
Remove the AutoPostBack="true" field in Gridview control. And make sure the Data-table have correct values for the columns and please see Text="" in your gridview labels . You need give values for the labels.
See this link , It's may helps you
Your problem is with your Template Fields as you cannot set values to them using a DataTable, change them to BoundFields or set AutoGenerateColumns="True"
Tried your code with my answer, it worked fine.

Categories

Resources