I have did a Edit/Update/Delete/Cancel in the gridbox. All the functionlaities are working fine. Except Updating.
When I Click, I get an error stating,
NullReferenceException was unhandled by the user code.
Object Reference not set to an instance of an object
Here is the Code for updating the data's
protected void Show_Grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(Show_Grid.DataKeys[e.RowIndex].Value.ToString());
TextBox title_txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Title");
TextBox Desc_Txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Description");
DropDownList Prior_Drop = (DropDownList)Show_Grid.Rows[e.RowIndex].FindControl("Priority");
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Show_Grid.EditIndex = -1;
BindData();
}
private void Update_todo(int id, string title, string desc, string prior)
{
string source = "Data Source=.\\SQLEXPRESS;AttachDbFilename=...//...//..//..//tododb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection dbconnect = new SqlConnection(source);
string query = "UPDATE todolist SET Title='" + title + "', Description='" + desc + "', Priority='" + prior + "' WHERE id =" + id + " ";
SqlCommand cmd = new SqlCommand(query, dbconnect);
dbconnect.Open();
cmd.ExecuteNonQuery();
}
In the Gridbox, while editing i gave TextBox with SingleLine for Title, TextBox with Multiline for Description & DropDown for Priority.
I get the error in this line
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Grid view markup
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="Desc_Txt" runat="server" Text='<%# Eval("Description") %>'
TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Priority">
<EditItemTemplate>
<asp:DropDownList ID="Prior_Drop" runat="server"
SelectedValue='<%# Eval("Priority") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Priority") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True"
ShowEditButton="True" />
</Columns>
</asp:GridView>
You are either not getting one or all of the controls title_txt, Desc_Txt or Prior_Drop
Check if they are null or not before accessing them
You can have a check before calling update like this, however you have to make sure that it does not break your functionality in any way
if(title_txt!=null && Desc_Text!=null && Prior_Drop!=null)
{
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Show_Grid.EditIndex = -1;
BindData();
}
Update
The mistake you are doing is, you are accessing the controls with wrong ids, use this and it will work
TextBox title_txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("title_txt");
TextBox Desc_Txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Desc_Txt");
DropDownList Prior_Drop = (DropDownList)Show_Grid.Rows[e.RowIndex].FindControl("Prior_Drop");
Related
I have a GridView within a LoginView that I am getting an Index Out Of Range error with. When I display the # of rows in the GridView it always shows 0 which is causing this error.
Is there something specific that I need to be doing to get a GridView
to properly work within a LoginView?
Below is the code that is being run when I click on a button in the GridView and the error only comes up on the GridView row = gv.Rows[e.RowIndex]; line. If I use only e.RowIndex I do not get the error and it will actually return the proper number. If I do gv.DataKeys.Count it will return the correct count. If I do gv.Rows.Count it will always be 0. I think it has something to do with a PostBack because if I do a row count in my page_load then it returns the correct count. Please let me know if there is anything else that you need for me to post?
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
GridViewRow row = gv.Rows[e.RowIndex];
string Id = (row.FindControl("lblID") as Label).Text;
string constr = System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"];
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("cardReview"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Id);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gv.EditIndex = -1;
this.BindGrid();
}
catch (Exception ex)
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
int index = e.RowIndex;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message + " " + index.ToString() + " " + gv.Rows.Count;
}
}
Below is the LoginView from the aspx page.
<asp:LoginView runat="server" ViewStateMode="Disabled" ID="ReviewLoginView">
<LoggedInTemplate>
<%--<AnonymousTemplate>--%>
<div>
<asp:GridView ID="gvReview" runat="server" AutoGenerateColumns="false" DataKeyNames="ID"
OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDeleting" EnableViewState="true"
EmptyDataText="No records have been added." AllowSorting="true" ShowHeaderWhenEmpty="true"
AlternatingRowStyle-BackColor="#e0e0e0" HeaderStyle-BackColor="#d0d0d0" ViewStateMode="Disabled"
EnableSortingAndPagingCallbacks="false">
<Columns>
<asp:TemplateField HeaderText="ID" ShowHeader="false" Visible="true">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' CssClass="cmsID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<asp:Label ID="lblSubmittedBy" runat="server" Text='<%# Eval("submittedBy") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblSubmittedDate" runat="server" Text='<%# Eval("submittedDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Was Observed?">
<ItemTemplate>
<asp:Label ID="lblWhatWasObserved" runat="server" Text='<%# Eval("whatWasObserved") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Action Was Taken?">
<ItemTemplate>
<asp:Label ID="lblWhatActionWasTaken" runat="server" Text='<%# Eval("whatActionWasTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Agreement Was Reached?">
<ItemTemplate>
<asp:Label ID="lblWhatAgreementWasReached" runat="server" Text='<%# Eval("whatAgreementWasReached") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Edit" CssClass="editbutton" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Review" ButtonType="Button" ShowDeleteButton="true" DeleteText="Review" />
</Columns>
</asp:GridView>
</div>
</LoggedInTemplate>
<%--</AnonymousTemplate>--%>
<AnonymousTemplate>
You must login to view submitted Observation Cards.
</AnonymousTemplate>
</asp:LoginView>
Below is the BindGrid()
private void BindGrid()
{
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"]);
{
SqlCommand comm = new SqlCommand("cardSelectNew2", conn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = comm;
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#Begin", "1/1/1950");
comm.Parameters.AddWithValue("#End", "12/31/2049");
comm.Parameters.AddWithValue("#Reviewed", "0");
comm.Parameters.AddWithValue("#OrderBy", "CH.id");
comm.Parameters.AddWithValue("#AscDesc", "Asc");
comm.Parameters.AddWithValue("#DateRange", "Last 30 Days");
comm.Connection = conn;
sda.SelectCommand = comm;
DataTable dt = new DataTable();
sda.Fill(dt);
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
gv.DataSource = dt;
gv.DataBind();
}
}
catch (Exception ex)
{
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message;
}
}
Below is my page_load
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
lblError.ForeColor = System.Drawing.Color.Black;
lblError.Text = "";
}
}
You are on the right track! But without seeing the whole class and markup we can only speculate.
Check that you are not clearing or rebuilding the data on the page load event handler, if the Grid and datasource is defined in the markup then it should cache or requery the data between page postbacks, check that you have set EnableRowCache on the GridView so that you dont have to re-query for the data during postbacks.
It looks like you are using the #OldSchool BindGrid() data load pattern, perhaps the simplest solution may be to ensure that the data is loaded first by calling BindGrid before you try to access the rows:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
this.BindGrid();
try
{
... delete logic
this.BindGrid(); // re-load after the change
}
catch (Exception ex)
{
...
}
}
Without enabling the row cache though you have to ensure that the same data is loaded into the grid in the same order or delete logic like this based on row index (instead of the primary key of the row) could result in you deleting the wrong data row.
I did work on a Search function where the user can type the item they want to search on a textbox, then hit a button to search.
the Search function is already working but for one option only (ContractNo), now I like to add a Dropdown list to add more options for the users to search (add: EmpID, TrainingCode etc)
here is the code for the aspx: (yes i only just included the codes that I think is necessary)
<div id="contentarea">
<p> Search Employee ID, Training Code, Contract Number<br/>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Contract Number</asp:ListItem>
<asp:ListItem>Training Code</asp:ListItem>
<asp:ListItem>Employee ID</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="searchText" runat="server" Height="16px" Width="146px"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />
<asp:Button ID="ButtonClear" runat="server" Text="Clear" OnClick="ButtonClear_Click" />
</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="TrainingCode" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
</a>
</Itemtemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="ContractNo" SortExpression="ContractNo">
<ItemTemplate>
<asp:Label ID="LabelContractNo" Text='<% #HighlightText(Eval("ContractNo").ToString()) %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TrainingCode" SortExpression="TrainingCode">
<ItemTemplate>
<asp:Label ID="LabelTrainingCode" runat="server" Text='<%# Eval("TrainingCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmpID" SortExpression="EmpID">
<ItemTemplate>
<asp:Label ID="LabelEmpID" runat="server" Text='<%# Eval("EmpID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractDate" SortExpression="ContractDate">
<ItemTemplate>
<asp:Label ID="LabelContractDate" runat="server" Text='<%# Eval("ContractDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractDuration" SortExpression="ContractDuration">
<ItemTemplate>
<asp:Label ID="LabelContractDuration" runat="server" Text='<%# Eval("ContractDuration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ServiceStart" SortExpression="ServiceStart">
<ItemTemplate>
<asp:Label ID="LabelServiceStart" runat="server" Text='<%# Eval("ServiceStart") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractValue" SortExpression="ContractValue">
<ItemTemplate>
<asp:Label ID="LabelContractValue" runat="server" Text='<%# Eval("ContractValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Served" SortExpression="Served">
<ItemTemplate>
<asp:Label ID="LabelServed" runat="server" Text='<%# Bind("Served") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbx %>" DeleteCommand="DELETE FROM [SCHOLARSHIPCONTRACT] WHERE [TrainingCode] = #TrainingCode" InsertCommand="INSERT INTO [SCHOLARSHIPCONTRACT] ([ContractNo], [TrainingCode], [EmpID], [ContractDate], [ContractDuration], [ServiceStart], [ContractValue], [Served]) VALUES (#ContractNo, #TrainingCode, #EmpID, #ContractDate, #ContractDuration, #ServiceStart, #ContractValue, #Served)" SelectCommand="SELECT * FROM [SCHOLARSHIPCONTRACT]" UpdateCommand="UPDATE [SCHOLARSHIPCONTRACT] SET [ContractNo] = #ContractNo, [EmpID] = #EmpID, [ContractDate] = #ContractDate, [ContractDuration] = #ContractDuration, [ServiceStart] = #ServiceStart, [ContractValue] = #ContractValue, [Served] = #Served WHERE [TrainingCode] = #TrainingCode" FilterExpression="ContractNo '%{0}%'">
<FilterParameters>
<asp:ControlParameter Name="ContractNo" ControlID="searchText" PropertyName="Text"/>
</FilterParameters>
</asp:SqlDataSource>
and the FULL C# backend code:
private string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
}
public string HighlightText(string InputText)
{
string Search_str = searchText.Text;
Regex RegExp = new Regex(Search_str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
return RegExp.Replace(InputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m) //this is just to highlight the item searched
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SearchString = searchText.Text;
}
protected void ButtonClear_Click(object sender, EventArgs e)
{
searchText.Text = "";
SearchString = "";
GridView1.DataBind();
}
Now im thinking to add an if statement maybe? on the FilterParameters? like
<% if (DropDownList1.text == "EmpID"){}
but Im not sure.. Can you suggest other methods please?? Let me know if you might need other codes from the program. Thank you in advance
Try to use generic options. Use DropDown to list all types (EmpID, TrainingCode). On the basis of type selection use Switch to filter by entered text in TextBox.
SearchString = searchText.Text;
Switch(types)
{
case EmpID:
DoOperation();
break;
case TrainingCode:
DoOperation();
break;
}
Ok , here the solution, it's working ok in my computer, I hope this is what you want to achieve. I put some comments in the code, read them
in aspx page , put this code
<div id="contentarea">
<p> Search Employee ID, Training Code, Contract Number<br/>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="ContractNo">Contract Number</asp:ListItem>
<asp:ListItem Value="TrainingCode">Training Code</asp:ListItem>
<asp:ListItem Value="EmpID">Employee ID</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="searchText" runat="server" Height="16px" Width="146px"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />
<asp:Button ID="ButtonClear" runat="server" Text="Clear" OnClick="ButtonClear_Click" />
</p>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
and this is the C# code in aspx.cs
private string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
}
public string HighlightText(string InputText)
{
string Search_str = searchText.Text;
Regex RegExp = new Regex(Search_str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
return RegExp.Replace(InputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m) //this is just to highlight the item searched
{
return ("<span class=highlight>" + m.Value + "</span>");
}
private DataTable GetData(string query)
{
// Read connection string from web.config file , Important, change the
//ConnectionStrings name here (testConnectionString)
// and replace it with your connection name , you can find it in web.config file
// in <connectionStrings> tag , you find it after this tag <add name="
string CS = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter sda = new SqlDataAdapter(query, con);
using (DataTable dt = new DataTable())
{
con.Open();
sda.Fill(dt);
return dt;
}
}
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SearchString = searchText.Text;
string columnName = DropDownList1.SelectedValue;
string searchSQL = "SELECT * FROM [SCHOLARSHIPCONTRACT] WHERE " + columnName + "= '" + SearchString + "'";
//bind the SCHOLARSHIPCONTRACT table data into GridView1
DataTable dt = this.GetData(searchSQL);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void ButtonClear_Click(object sender, EventArgs e)
{
searchText.Text = "";
SearchString = "";
GridView1.DataBind();
}
I am trying to save grid view text box value and two other text box that are filled by user that are Total Marks and Marks Scored to data base am not sure how to pass back the values of that textboxs to data base on one click of submit
DB where the value to be saved are
Studentname RegNo TotalMarks Marksscored
asdsa 22 125 22
My Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtStudent_Name" runat="server" Text='<%# Eval("StudentFirstName") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register Number">
<ItemTemplate>
<asp:TextBox ID="txtreg_number" runat="server" Text='<%# Eval("StudentRegID") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Marks">
<ItemTemplate>
<asp:TextBox ID="txttotal_marks" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marks Scored">
<ItemTemplate>
<asp:TextBox ID="txtmarks_scored" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");
string UserID = txtUsrId.Text;
string q="insert into details (name) values('"+UserID+"')";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
I have a DataGrid with a datasource on page load, but when I make changes to the Textboxes within the datagrid, I don't know how to get those new textbox.text.
I don't what to change the new datasource to??
So My question is how Do I update the datasource and save my new edited TextBox.Text field??...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
CustomerDao dao = new CustomerDao();
currentCustomer = dao.SelectAll().First(x => x.CustomerID == 3) as Customer;
//Assigning SQL Datasource to Gridview
SqlDataSource1.SelectCommand = "SELECT CustomerID, FirstName, MiddleIntial, LastName, DateOfBirth, TaxID, GenderId FROM Customer " +
"WHERE CustomerID = " + 3;
ClientGridView.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
//Set a new datasource here??
string firstName = string.Empty;
string middileInitial = string.Empty;
string lastname = string.Empty;
string date = string.Empty;
DateTime dateOfBirth;
string taxId = string.Empty;
string strGender = string.Empty;
int genderId = 0;
foreach (GridViewRow r in ClientGridView.Rows)
{
firstName = ((TextBox)r.FindControl("txtFirstName")).Text;
middileInitial = ((TextBox)r.FindControl("txtMiddleInitial")).Text;
lastname = ((TextBox)r.FindControl("txtLastName")).Text;
date = ((TextBox)r.FindControl("txtDateOfBirth")).Text;
taxId = ((TextBox)r.FindControl("txtTaxID")).Text;
strGender = ((TextBox)r.FindControl("txtGenderID")).Text;
}
}
I have been searching for hours and found nothing really relating to my situation. I also feel like there should be a much better way then to implement all the event handlers for _RowEditing and _RowUpdating and I have tried these but none of their event handlers fired anyway....
EDIT: Heres my GridView XAML
<asp:GridView runat="server" ID="ClientGridView" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" OnRowEditing="ClientGridView_RowEditing"
Width="650px" PageSize="20" CssClass="gridView" DataSourceID="SqlDataSource1" OnDataBound="ClientGridView_DataBound" >
<Columns>
<asp:TemplateField HeaderText="First Name" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtFirstName" Text='<%# Bind("FirstName") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Initial" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtMiddleInitial" Text='<%# Bind("MiddleIntial") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtLastName" Text='<%# Bind("LastName") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of birth" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDateOfBirth" Text='<%# Bind("DateOfBirth") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tax ID" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTaxID" Text='<%# Bind("TaxID") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender ID" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtGenderID" Text='<%# Bind("GenderId") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the SQLDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false"
ConnectionString=myconnectionString;User Id=userID;Password=pass; Persist Security Info=false;" />
I have a GridView1, which I am binding from code behind. The one of the columns in the GridView depends on Label1.Text as follows:
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name, " + Label1.Text + " FROM Home_Profile_Master", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
The aspx code for the same is :
<asp:TemplateField HeaderText="Location_Profile_Name"
SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
I am getting an error in the aspx page as: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Home_Profile'.
I am not able to figure out what the mistake is. Kindly Help...! thank you.
you missed 'Home_Profile' in the query.
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name," + Label1.Text + " as Home_Profile FROM Home_Profile_Master", con);
you shuld have Home_Profile column in data table try this
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name,Home_Profile, " + Label1.Text + " FROM Home_Profile_Master", con);