Send column number value to asp MaxLength - c#

I have a column in database where integer values are stored (4, 6, 8, and NULL).
These integer values are supposed to be max allowed length of TextBox, this is the table.
This is code from c# where I passed Characteristic names and integers(max number of places for textboxes from database dynamically) for now.
protected void ddlBC_SelectedIndexChanged(object sender, EventArgs e)
{
//ddlKar.Items.Clear();
LogicTableAdapters.getLvLOneIntegerTableAdapter getKar = new LogicTableAdapters.getLvLOneIntegerTableAdapter();
DataTable dtKar = getKar.getLvLOneInteger(ddlBC.SelectedValue);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]{ new DataColumn("CharacteristicName", typeof(string)) new DataColumn("MaxNoPlaces", typeof(string))});
foreach (DataRow dr in dtKar.Rows)
{
dt.Rows.Add(dr["CharacteristicName"].ToString(), dr["MaxNoPlaces"].ToString());
}
gvKarakteristike.DataSource = dt;
gvKarakteristike.DataBind();
}
This is the ASPX markup:
<asp:GridView ID="gvKarakteristike" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="LevelID" OnRowDataBound="gvKarakteristike_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Characteristics">
<ItemTemplate>
<asp:Label ID="Characteristics" runat="server" Width="150px" Height="30px" Font-Names="Georgia" margin-Left="100px" Text='<%# Bind("CharacteristicName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="ddlOpis" AppendDataBoundItems="true" Width="142px" Height="35px" Font-Names="Georgia" margin-Left="100px" runat="server">
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
<asp:TextBox ID="txtBoxOpis" runat="server" Font-Names="Georgia" margin-Left="100px" Text="" MaxLength='<%# Bind("MaxNoPlaces") %>'></asp:TextBox>
</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>
I need to this dynamically directly from database because database will grow over time so will the number of textboxes.
The problem is with this part of the code:
<asp:TextBox ID="txtBoxOpis" runat="server" Font-Names="Georgia" margin-Left="100px" Text="" MaxLength='<%# Bind("MaxNoPlaces") %>'></asp:TextBox>
There's an error when I run the app there:
An exception of type 'System.InvalidCastException' occurred in App_Web_kn224wf0.dll but was not handled in user code
I think the problem is when the NULL value is send from the database to the asp, then it can convert it to MaxLength.
Can someone please help me to resolve this issue ?
Thanks in advance !

TextBox.MaxLength property expects value type of int, as in this declaration:
public virtual int MaxLength { get; set; }
Because MaxNoPlaces column declared with string data type in DataTable bound with GridView.DataBind() method, you will encounter InvalidCastException when binding it directly to the corresponding property. You should use typeof(int) and do integer conversion such like Convert.ToInt32() or int.Parse() before binding:
dt.Columns.AddRange(new DataColumn[2]{ new DataColumn("CharacteristicName", typeof(string)),
new DataColumn("MaxNoPlaces", typeof(int))});
foreach (DataRow dr in dtKar.Rows)
{
// perform integer conversion
dt.Rows.Add(dr["CharacteristicName"].ToString(), Convert.ToInt32(dr["MaxNoPlaces"]));
}
If you done the conversion before binding to textbox control, then binding conversion like <asp:TextBox runat="server" MaxLength='<%# Convert.ToInt32(Bind("MaxNoPlaces")) %>' ... /> becomes unnecessary.

Related

Changing dropdownlist selected index in Gridview, conected (to getting value from) second DropDownlist

My page which to do this:
I want to connect outside dropdown list to inside of gridview dropdownlist. When selec item from outside dropdownlist, must be change inside dropdown list item automaticaly. I've tried a lot thing to change. Can you give me help. Thanks.
My ASPX page.(Don't answer connected this code)
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="Kimlik" GridLines="Horizontal"
onrowdatabound="GridView4_RowDataBound" ForeColor="#333333" Visible="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Öd.Nu.">
<EditItemTemplate>
<asp:TextBox ID="TextBox1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Öğrenci Adı Soyadı">
<EditItemTemplate>
<asp:TextBox ID="TextBox2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Odev Sonucu">
<EditItemTemplate>
<asp:TextBox ID="TextBox3x" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1x" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ödev Sonuç Açıklaması">
<EditItemTemplate>
<asp:TextBox ID="TextBox4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
<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>
on Selected Index Change Event of Outer drop down add below code
protected void OurterDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView.Rows)
{
DropDownList innerDropdown = (DropDownList)row.FindControl("innedDropedDOwnID");
innerDropdown .ClearSelection(); //making sure the previous selection has been cleared
innerDropdown .Items.FindByValue(OurterDropDown.SelectedValue).Selected = true;
}
}
Make sure you have set AutoPostBack="true" outside DropDownList and then try this code in RowDataBound event:
protected void GridView4_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if your row is not a Header/Footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get Dropdownlist from gridview
DropDownList DropDownList1x = e.Row.FindControl("DropDownList1x") as DropDownList;
// ddlouter is your outside DropDownList
DropDownList1x.Items.FindByValue(ddlOuter.SelectedValue).Selected = true;
}
}

No Overload for method which takes 4 arguments

I am trying to update gridview. Here, I have used 3 tier architecture method.
Here is my GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ResllerID"
ForeColor="#333333" GridLines="None" OnRowDeleting="DeleteRecord" EmptyDataText="There are no data records to display."
AllowPaging="True" AllowSorting="True" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Reseller Name" SortExpression="ResellerName">
<EditItemTemplate>
<asp:TextBox ID="ResellerTextBox" runat="server" Text='<%# Bind("ResellerName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ResellerName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number" SortExpression="MobileNumber">
<EditItemTemplate>
<asp:TextBox ID="MobileTextBox" runat="server" Text='<%# Bind("MobileNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("MobileNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reference Number" SortExpression="ReferenceNumber">
<EditItemTemplate>
<asp:TextBox ID="ReferenceTextBox" runat="server" Text='<%# Bind("ReferenceNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ReferenceNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
Here is my code: I am getting error ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text); It says No Overload for method which takes 4 arguments
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ResellerBL.GetResellers();
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int resellerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
TextBox mobileNumber = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
TextBox referenceNumber = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];
ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text);
GridView1.EditIndex = -1;
GridView1.DataSource = ResellerBL.GetResellers();
GridView1.DataBind();
}
ResellerBL code:
public static void UpdateReseller(Reseller reseller)
{
string query = "UPDATE [Resellers] SET [ResellerName] = #ResellerName, [ReferenceNumber] = #ReferenceNumber WHERE [ResellerID] = #ResellerID";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#ResellerName", SqlDbType.Text).Value = reseller.ResellerName;
cmd.Parameters.AddWithValue("#MobileNumber", SqlDbType.Text).Value = reseller.MobileNumber;
cmd.Parameters.AddWithValue("#ReferenceNumber", SqlDbType.Text).Value = reseller.ReferenceNumber;
cmd.Parameters.AddWithValue("#ResllerID", SqlDbType.Text).Value = reseller.ResllerID;
DbUtility.UpdateDb(cmd);
}
You are calling it with four arguments:
ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text);
But it only accepts one:
public static void UpdateReseller(Reseller reseller)
Two options are
Create a new reseller object and pass that:
.
var myreseller = New Reseller();
myresller.Id = resellerId;
//etc
ResellerBL.UpdateReseller(myreseller);
OR
Modify the (or add an overloaded) method to take the four arguments:
.
public static void UpdateReseller(int resellerId, string resellerName, string resellerMobile, string resellerRefNum)
Your UpdateReseller method takes a single parameter: A reseller.
If you want to be able to pass individual parts to the method, you need to modify the signature or create an overload with the appropriate parameters.

Unable to get data from TextBox/DDL in Gridview

I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;

how to show values from database in a dropdownlist which is inside a gridview?

I'm trying get values from database to dropdownlist which is placed inside a gridview item template. I'm using gridview to take values from user. In one column I'm using dropdownlist from which user has to select an item. According to the selection its cost price will populate automatically on the other column. But I'm unable to get the values in dropdownlist and getting an error "Object reference not set to an instance of an object."
Aspx code given below:
<asp:GridView ID="gvItemList" runat="server" ShowFooter="True" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" ViewStateMode="Enabled" CssClass="newStyle9" style="text-align: center" OnRowDeleting="gvItemList_RowDeleting" OnRowDataBound="gvItemList_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sl No" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server"
Text='<%# Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="128px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Date">
<ItemTemplate>
<asp:TextBox ID="txtRequiredDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="txtRequiredDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtRequiredDate">
</ajaxToolkit:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Quantity">
<ItemTemplate>
<asp:TextBox ID="txtRequiredQuantity" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost Price">
<ItemTemplate>
<asp:Label ID="lblCostPrice" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UoM Code">
<ItemTemplate>
<asp:Label ID="lblUomCode" runat="server">Manual</asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" Text="Add New Item"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code under row databound is given below:
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
DS_SiteDataTableAdapters.tbl_ItemTableAdapter item;
item = new DS_SiteDataTableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItem();
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
ddlItem.DataSource = dt; //here I'm getting an error "Object reference not set to an instance of an object."
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
}
Any help is greatly appreciated!
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Select Country"));
}
Hope this helps!
just check below condition in your method
if (e.Row.RowType == DataControlRowType.DataRow)
{ your code }
I hope it will help u
As mentioned in the comments, you are trying to use a null object, thinking that it has a referenced object.
You are doing something like this:
public class Example
{
public void MyMethod()
{
}
}
Example myExample= null;
myExample.MyMethod();
You will get "Object reference not set to an instance of an object." which is the same as NullReferenceException because you are calling a method on a reference type which is null.
You are getting Object Reference error because you are not checking for DataRow in your gridview. Because of that it is trying to find the dropdown in header where it is not present and thus you are getting Dropdown object as Null.
Add this condition to your gvItemList_RowDataBound event:-
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Your rest code
}
}
try this you get null reference because you are not able to find ddlItem control
at line
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
so instead you can try as below
DropDownList ddlItem = (DropDownList)GridView.Rows[rowindex].FindControl("ddlItem"))

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