on add button click data insert twice - c#

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyManageConnectionString"].ToString());
string InstituteId = HttpContext.Current.Request.Cookies["InstituteId"].Value;
protected void Page_Load(object sender, EventArgs e)
{
((Label)Master.FindControl("lblPageName")).Text = "Employee List";
((Label)Master.FindControl("lblPageName")).ForeColor = System.Drawing.Color.Black;
((Label)Master.FindControl("lblPageName1")).Text = " Employee List";
if (Request.Cookies["InstituteId"] == null)
{
string OriginalUrl = HttpContext.Current.Request.RawUrl;
string LoginPageUrl = "INlogin.aspx";
HttpContext.Current.Response.Redirect(String.Format("{0}?R={1}", LoginPageUrl, OriginalUrl));
}
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string strQuery = "select * from tblEmployee where InstituteId=#InstituteId";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#InstituteId", InstituteId);
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
//SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string ActivationCode = Guid.NewGuid().ToString();
string txtEmployeeName = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeName")).Text;
string txtEmployeeAddress = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeAddress")).Text;
string txtEmployeeEmailId = ((TextBox)gvEmpList.FooterRow.FindControl("txtEmployeeEmailId")).Text;
string txtMobile = ((TextBox)gvEmpList.FooterRow.FindControl("txtMobile")).Text;
string txtBirthDate = ((TextBox)gvEmpList.FooterRow.FindControl("txtBirthDate")).Text;
string txtdateOfJoining = ((TextBox)gvEmpList.FooterRow.FindControl("txtdateOfJoining")).Text;
string txtExperiance = ((TextBox)gvEmpList.FooterRow.FindControl("txtExperiance")).Text;
string txtLastSchoolDetails = ((TextBox)gvEmpList.FooterRow.FindControl("txtLastSchoolDetails")).Text;
string txtSalaryDetails = ((TextBox)gvEmpList.FooterRow.FindControl("txtSalaryDetails")).Text;
bool chkmerriageStatus = ((CheckBox)gvEmpList.FooterRow.FindControl("chkmerriageStatus")).Checked;
string txtNationality = ((TextBox)gvEmpList.FooterRow.FindControl("txtNationality")).Text;
try
{
//SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
//con.Open();
//cmd.Connection = con;
cmd.CommandText = "INSERT INTO tblEmployee (InstituteId, EmployeeName, EmployeeAddress, EmployeeEmailId, Mobile, BirthDate, dateOfJoining, Experiance, LastSchoolDetails, SalaryDetails, merriageStatus, Nationality, ActivationCode, ActivationStatus, Password) VALUES (#InstituteId, #EmployeeName, #EmployeeAddress, #EmployeeEmailId, #Mobile, #BirthDate, #dateOfJoining, #Experiance, #LastSchoolDetails, #SalaryDetails, #merriageStatus, #Nationality, #ActivationCode, #ActivationStatus, #Password);" + "select * from tblEmployee where InstituteId=#InstituteId";
cmd.Parameters.AddWithValue("#InstituteId", InstituteId);
cmd.Parameters.AddWithValue("#EmployeeName", txtEmployeeName);
cmd.Parameters.AddWithValue("#EmployeeAddress", txtEmployeeAddress);
cmd.Parameters.AddWithValue("#EmployeeEmailId", txtEmployeeEmailId);
cmd.Parameters.AddWithValue("#Mobile", txtMobile);
cmd.Parameters.AddWithValue("#BirthDate", txtBirthDate);
cmd.Parameters.AddWithValue("#dateOfJoining", txtdateOfJoining);
cmd.Parameters.AddWithValue("#Experiance", txtExperiance);
cmd.Parameters.AddWithValue("#LastSchoolDetails", txtLastSchoolDetails);
cmd.Parameters.AddWithValue("#SalaryDetails", txtSalaryDetails);
cmd.Parameters.AddWithValue("#merriageStatus", chkmerriageStatus);
cmd.Parameters.AddWithValue("#Nationality", txtNationality);
cmd.Parameters.AddWithValue("#ActivationCode", ActivationCode);
cmd.Parameters.AddWithValue("#ActivationStatus", false);
string GTPassword = System.Web.Security.Membership.GeneratePassword(8, 3);
cmd.Parameters.AddWithValue("#Password", GTPassword);
//int result = cmd.ExecuteNonQuery();
//con.Close();
//if (result == 1)
//{
// sendActivation(ActivationCode, txtEmployeeName, txtEmployeeEmailId);
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Registration Successfull')", true);
//}
//else {
// Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Registration Fail')", true);
//}
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
//BindData();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
When the add button is clicked btnAdd_click inserts data twice. Also I am not getting any exception errors in btnadd_click code.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="dvGrid" style="overflow-x: scroll; Overflow: scroll;">
<asp:UpdatePanel ID="upEmployeeList" runat="server">
<ContentTemplate>
<asp:GridView Width="100%" ID="gvEmpList" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId" CssClass="gvmydatagrid" PagerStyle-CssClass="gvpager" HeaderStyle-CssClass="gvheader" RowStyle-CssClass="gvrows" ShowFooter="True" OnPageIndexChanging="gvEmpList_PageIndexChanging" OnRowEditing="gvEmpList_RowEditing" OnRowUpdating="gvEmpList_RowUpdating" OnRowCancelingEdit="gvEmpList_RowCancelingEdit" AllowPaging="True" PageSize="25">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument='<%# Eval("EmployeeId")%>'
OnClientClick="return confirm('Do you want to delete?')"
Text="Delete" OnClick="lnkRemove_Click"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="EmployeeId" InsertVisible="False" SortExpression="EmployeeId">
<EditItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text='<%# Eval("EmployeeId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text='<%# Bind("EmployeeId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="InstituteId" SortExpression="InstituteId">
<EditItemTemplate>
<asp:Label ID="txtInstituteId" runat="server" Text='<%# Bind("InstituteId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblInstituteId" runat="server" Text='<%# Bind("InstituteId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="EmployeeName" SortExpression="EmployeeName">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeAddress" SortExpression="EmployeeAddress">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeAddress" runat="server" Text='<%# Bind("EmployeeAddress") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeAddress" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeAddress" runat="server" Text='<%# Bind("EmployeeAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeEmailId" SortExpression="EmployeeEmailId">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeEmailId" runat="server" Text='<%# Bind("EmployeeEmailId") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeEmailId" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeEmailId" runat="server" Text='<%# Bind("EmployeeEmailId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile" SortExpression="Mobile">
<EditItemTemplate>
<asp:TextBox ID="txtMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BirthDate" SortExpression="BirthDate">
<EditItemTemplate>
<asp:TextBox ID="txtBirthDate" runat="server" Text='<%# Bind("BirthDate") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblBirthDate" runat="server" Text='<%# Bind("BirthDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dateOfJoining" SortExpression="dateOfJoining">
<EditItemTemplate>
<asp:TextBox ID="txtdateOfJoining" runat="server" Text='<%# Bind("dateOfJoining") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtdateOfJoining" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbldateOfJoining" runat="server" Text='<%# Bind("dateOfJoining") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experiance" SortExpression="Experiance">
<EditItemTemplate>
<asp:TextBox ID="txtExperiance" runat="server" Text='<%# Bind("Experiance") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExperiance" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblExperiance" runat="server" Text='<%# Bind("Experiance") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastSchoolDetails" SortExpression="LastSchoolDetails">
<EditItemTemplate>
<asp:TextBox ID="txtLastSchoolDetails" runat="server" Text='<%# Bind("LastSchoolDetails") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastSchoolDetails" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblLastSchoolDetails" runat="server" Text='<%# Bind("LastSchoolDetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalaryDetails" SortExpression="SalaryDetails">
<EditItemTemplate>
<asp:TextBox ID="txtSalaryDetails" runat="server" Text='<%# Bind("SalaryDetails") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSalaryDetails" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblSalaryDetails" runat="server" Text='<%# Bind("SalaryDetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="merriageStatus" SortExpression="merriageStatus">
<EditItemTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server" Checked='<%# Bind("merriageStatus") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server"></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkmerriageStatus" runat="server" Checked='<%# Bind("merriageStatus") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nationality" SortExpression="Nationality">
<EditItemTemplate>
<asp:TextBox ID="txtNationality" runat="server" Text='<%# Bind("Nationality") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNationality" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblNationality" runat="server" Text='<%# Bind("Nationality") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" SortExpression="Password">
<EditItemTemplate>
<asp:TextBox ID="txtPassword" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</EditItemTemplate>
<%--<FooterTemplate>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</FooterTemplate>--%>
<ItemTemplate>
<asp:Label ID="lblPassword" runat="server" Text='<%# Bind("Password") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="gvheader" />
<PagerStyle CssClass="gvpager" />
<RowStyle CssClass="gvrows" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvEmpList" />
</Triggers>
</asp:UpdatePanel>
</div>
When I click on add button, footer item data will insert into my database but is insert twice. It is in debug mode and jumping around everywhere.
it show "The process or thread has changed since last step."

You are sending the insert command again by calling gvEmpList.DataSource = GetData(cmd); inside btnAdd_Click. Please check it. The cmd object inside btnAdd_Click is an insert command.

Remove following code from btnAdd_Click
gvEmpList.DataSource = GetData(cmd);
gvEmpList.DataBind();
And call following method
BindData();

Related

Use child footer row to add new record to a nested gridview

I have a nested grid views:
<asp:GridView ID="gvRequisitions" runat="server" AutoGenerateColumns="false"
DataKeyNames="PurchaseRequisitionID" OnRowDataBound="OnRowDataBound" ShowFooter="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor:pointer" src="../images/plus.png" width="12" height="12" />
<asp:Panel ID="pnlItems" runat="server" Style="display: none">
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" ShowFooter="true"
OnRowDataBound="gvItems_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("ItemID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddItem" runat="server" OnClick="addItem" Text="add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Code">
<ItemTemplate>
<asp:Label ID="lblItemCode" runat="server" Text='<%# Eval("ItemCode") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemCode" runat="server" Visible="true" Width="100"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'
Width="225"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="225"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date req.">
<ItemTemplate>
<asp:Label ID="lblDateRequired" runat="server" Text='<%# Eval("DateRequired") %>'
Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDateRequired" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Measure">
<ItemTemplate>
<asp:Label ID="lblMeasure" runat="server" Text='<%# Eval("MeasureID") %>'
Width="120" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMeasure" runat="server" Width="120"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity") %>' Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Label ID="lblCostPerUnit" runat="server" Text='<%# Eval("CostPerUnit") %>' Width="75"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostPerUnit" runat="server" Width="75"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text='<%# Eval("Total") %>' Width="120"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No Items For this Requisition</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblPurchaseRequisitionID" runat="server" Text='<%# Eval("PurchaseRequisitionID") %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddReq" runat="server" Text="Add" OnClick="addPurreq" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Requested By">
<ItemTemplate>
<asp:Label ID="lblRequestor" runat="server" Text='<%# Eval("Requestor") %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlRequestor" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDepartmentID" runat="server" Text='<%# Eval("DepartmentID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDepartment" runat="server" Width="200" ></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Budget">
<ItemTemplate>
<asp:Label ID="lblBudgetID" runat="server" Text='<%# Eval("BudgetID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlBudget" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Supplier">
<ItemTemplate>
<asp:Label ID="lblSupplierID" runat="server" Text='<%# Eval("SupplierID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSupplier" runat="server" Width="200"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created">
<ItemTemplate>
<asp:Label ID="lblDateCreated" runat="server" Text='<%# Eval("DateCreated","{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In code behind I have:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string purchaseRequisitionID = gvRequisitions.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvItems = (GridView)e.Row.FindControl("gvItems");
// new code to send reference to gvItems_RowDataBound
gvItems.RowDataBound += new GridViewRowEventHandler(gvItems_RowDataBound);
int id = Convert.ToInt32(purchaseRequisitionID);
using (SqlConnection conn = new SqlConnection(constr))
{
using(SqlCommand comm = new SqlCommand("procItems_CRUD"))
{
comm.Parameters.AddWithValue("#Action", "SELECT");
comm.Parameters.AddWithValue("#ID", id);
using(SqlDataAdapter sda = new SqlDataAdapter())
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
sda.SelectCommand = comm;
using(DataTable dt = new DataTable())
{
sda.Fill(dt);
gvItems.DataSource = dt;
gvItems.DataBind();
}
}
}
}
}
}
And:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMeasure = e.Row.FindControl("ddlMeasure") as DropDownList;
if(ddlMeasure == null)
{
}
}
}
But I cannot see the drop down list as it returns a null value (as I know it is not a DataRow) but how can I see the footer row and the elements in footer row so that I can add another Item to the order/populate DropDownList etc.
Have been trying to sort this for some time and cannot find a working solution so any pointer(s) will be very much appreciated.
You need to use DataControlRowType.Footer.
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a footer row
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlMeasure = e.Row.FindControl("ddlMeasure") as DropDownList;
if (ddlMeasure != null)
{
ddlMeasure.Items.Insert(0, new ListItem("DLL Found!", "-1"));
}
}
}

Add info using textbox into gridview after retrieving data from database C#

I'm retrieving data from database into the grid for 5 column, there is another 3 columns beside that which I want to fill in using textbox input (using different button).
How to fetch the input from the textbox into the grid after I retrieve the data from database?
Here is the front looks like:
Here is the coding:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="BNE No: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="BNE No: "></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search From Database" />
<br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Insert to Grid" OnClick="Button3_Click" />
<br />
<%--<asp:Table ID="Table1" runat="server">
</asp:Table>--%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="BNE No">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#Bind("BNENo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ECN No">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%#Bind("KVNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rec Date">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%#Bind("ReceivedDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Issued Date">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%#Bind("IssuedDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%#Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
Here is the behind code where I use to retrieve the data by using button 1
protected void Button1_Click(object sender, EventArgs e)//this Button use To call multiple data from database named tblBNE into GridView
{
count = 0;
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [BNENo],[KVNo],[ReceivedDate],[IssuedDate],[Status] FROM [tblBNE] where BNENo='" + TextBox1.Text + "' or BNENo='" + TextBox2.Text + "' ";
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (count == 0)
{
Label3.Text = "record not found";
}
}
So, I want to use button 3 = insert to grid to fill into label9 to 11 using textbox3 to 5. How can I do that?
Thank you in advance :)

Unable to cast object of type 'AllProjects_Result' to type 'Project'

i found many article and i make this code
i have this error
Unable to cast object of type 'AllProjects_Result' to type 'Project'.
<asp:GridView ID="GVAllProjects" runat="server"
OnRowDataBound="GVAllProjects_RowDataBound"
OnRowDeleting="GVAllProjects_RowDeleting"
OnRowEditing="GVAllProjects_RowEditing"
OnRowUpdating="GVAllProjects_RowUpdating"
AutoGenerateColumns="False" AllowPaging="True" PageSize="5" DataKeyNames="ID">
<Columns>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblProID" Visible="false" runat="server" Text='<%# Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="المشروعات" ItemStyle-Width="150" >
<ItemTemplate>
<asp:Label ID="lblProjectName" runat="server" Text='<%# Eval("ProjectName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProjectName" runat="server" Text='<%# Eval("ProjectName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="الموقع" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblDistrictName" runat="server" Text='<%# Eval("DistrictName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlDistrictName" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valDistrictName" runat="server" ControlToValidate="ddlDistrictName"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDistrictNameNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valDistrictNameNew" runat="server" ControlToValidate="ddlDistrictNameNew"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="المساحات" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblAreas" runat="server" Text='<%# Eval("Areas")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAreas" runat="server" Text='<%# Eval("Areas") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="نظام السداد" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblPaymentSystem" runat="server" Text='<%# Eval("PaymentSystem")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPaymentSystem" runat="server" Text='<%# Eval("PaymentSystem") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="تاريخ الاستلام" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblReceivedDate" runat="server" Text='<%# Eval("ReceivedDate", "{0:d}")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDate" runat="server"></asp:TextBox>
<asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/images/-calendar.png" ImageAlign="Bottom" />
<ajaxToolkit:calendarextender popupbuttonid="imgPopup" id="CalendarExtender1" runat="server" targetcontrolid="txtEditDate"
format="MM/dd/yyyy" enabled="true" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDate" runat="server"></asp:TextBox>
<asp:ImageButton runat="server" ID="imgPopup" ImageUrl="~/images/-calendar.png" ImageAlign="Bottom" />
<ajaxToolkit:calendarextender id="CalendarExtender2" runat="server"
targetcontrolid="txtAddDate" popupbuttonid="imgPopup" enabled="true" format="dd/MM/yyyy" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="تصنيف العقار" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblClassification" runat="server" Text='<%# Eval("PropertyClassification")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtClassification" runat="server" Text='<%# Eval("PropertyClassification") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="صورة المشروع" ItemStyle-Width="150">
<ItemTemplate>
<img src='ProjectsImages/<%# Eval("ProjectImage") %>' style="width:120px;height:120px;" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="UploadPhoto" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="الغرض" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblPurposeName" runat="server" Text='<%# Bind("PurposeName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPurposeName" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valPurposeName" runat="server" ControlToValidate="ddlPurposeName"
Display="Dynamic" ErrorMessage="PurposeName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlPurposeNameNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valClassificationNew" runat="server" ControlToValidate="ddlPurposeNameNew"
Display="Dynamic" ErrorMessage="DistrictName is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="النوع" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblTypes" runat="server" Text='<%# Bind("TypeName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlTypes" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valTypes" runat="server" ControlToValidate="ddlTypes"
Display="Dynamic" ErrorMessage="Types is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTypesNew" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="valTypesNew" runat="server" ControlToValidate="ddlTypesNew"
Display="Dynamic" ErrorMessage="Types is required." ForeColor="Red" SetFocusOnError="True"
ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this is my code :
protected void GVAllProjects_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList ddlDistrictName = null;
DropDownList ddlPurposeName = null;
DropDownList ddlTypes = null;
if (e.Row.RowType == DataControlRowType.Footer)
{
ddlDistrictName = e.Row.FindControl("ddlDistrictNameNew") as DropDownList;
ddlPurposeName = e.Row.FindControl("ddlPurposeNameNew") as DropDownList;
ddlTypes = e.Row.FindControl("ddlTypesNew") as DropDownList;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
ddlDistrictName = e.Row.FindControl("ddlDistrictName") as DropDownList;
ddlPurposeName = e.Row.FindControl("ddlPurposeName") as DropDownList;
ddlTypes = e.Row.FindControl("ddlTypes") as DropDownList;
}
if (ddlDistrictName != null)
{
using (AlamaarRealEstateEntities context = new AlamaarRealEstateEntities())
{
ddlDistrictName.DataSource = context.Districts.ToList();
ddlDistrictName.DataTextField = "DistrictName";
ddlDistrictName.DataValueField = "ID";
ddlDistrictName.DataBind();
ddlPurposeName.Items.Insert(0, new ListItem(""));
ddlPurposeName.DataSource = context.Purposes.ToList();
ddlPurposeName.DataTextField = "PurposeName";
ddlPurposeName.DataValueField = "ID";
ddlPurposeName.DataBind();
ddlTypes.Items.Insert(0, new ListItem(""));
ddlTypes.DataSource = context.Types.ToList();
ddlTypes.DataTextField = "TypeName";
ddlTypes.DataValueField = "ID";
ddlTypes.DataBind();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddlDistrictName.SelectedValue = ((Project)(e.Row.DataItem)).DistrictID.ToString();
ddlPurposeName.SelectedValue = ((Project)(e.Row.DataItem)).PurposeID.ToString(); ;
ddlTypes.SelectedValue = ((Project)(e.Row.DataItem)).TypeID.ToString();
}
}
}
}
void BindGrid()
{
using (AlamaarRealEstateEntities context = new AlamaarRealEstateEntities())
{
if (context.Projects.Count() > 0)
{
GVAllProjects.DataSource = context.AllProjects().ToList();
GVAllProjects.DataBind();
}
else
{
var obj = new List<Project>();
obj.Add(new Project());
// Bind the DataTable which contain a blank row to the GridView
GVAllProjects.DataSource = obj;
GVAllProjects.DataBind();
int columnsCount = GVAllProjects.Columns.Count;
GVAllProjects.Rows[0].Cells.Clear();// clear all the cells in the row
GVAllProjects.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
GVAllProjects.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
//You can set the styles here
GVAllProjects.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
GVAllProjects.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
GVAllProjects.Rows[0].Cells[0].Font.Bold = true;
//set No Results found to the new added cell
GVAllProjects.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
}
}
}
the error here in this lines :
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddlDistrictName.SelectedValue = ((Project)(e.Row.DataItem)).DistrictID.ToString();
ddlPurposeName.SelectedValue = ((Project)(e.Row.DataItem)).PurposeID.ToString(); ;
ddlTypes.SelectedValue = ((Project)(e.Row.DataItem)).TypeID.ToString();
}
}
any help is appreciated.

How to hide duplicate data from Gridview?

how am i be able to hide those duplicate columns using gridview command?
im using
nested gridview and left Outer Join on sqlcommand i joined two database.. so yeah this is my next problem
this is my code
protected void NewConnection()
{
SqlCommand cmd = new SqlCommand("SELECT a.*,b.ID,b.Firstname,b.Middlename,b.Lastname,b.Friendswith,b.Amount from [User_TBL_DB] a LEFT OUTER JOIN [Friends_TBL_DB] b ON a.ID=b.Friendswith", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
GroupGridView(GridView1.Rows, 0,0);
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
GridView1.Columns[9].Visible = false;
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
foreach (GridViewRow Separate in GridView1.Rows)
{
GridView gv2 = ((GridView)Separate.FindControl("GridView2"));
gv2.DataSource = ds;
gv2.DataBind();
string strfirstname = ((Label)Separate.FindControl("lblfirstname")).Text;
string strmiddlename=((Label)Separate.FindControl("lblmiddlename")).Text;
string strlastname = ((Label)Separate.FindControl("lbllastname")).Text;
string strage = ((Label)Separate.FindControl("lblage")).Text;
string strsex = ((Label)Separate.FindControl("lblsex")).Text;
string stramount = ((Label)Separate.FindControl("lblamount")).Text;
string strID1 = ((Label)Separate.FindControl("lblid")).Text;
foreach (GridViewRow grouplist in gv2.Rows)
{
string strID2 = ((Label)grouplist.FindControl("lblfriendswith2")).Text;
if (strID1 == strID2)
{
grouplist.Visible = true;
}
else
{
grouplist.Visible = false;
}
}
}
}
and this is my asp for gridview1 and gridview2
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Firstname" SortExpression="Firstname">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Firstname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblfirstname" runat="server" Text='<%# Bind("Firstname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middlename" SortExpression="Middlename">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Middlename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblmiddlename" runat="server" Text='<%# Bind("Middlename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lastname" SortExpression="Lastname">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Lastname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllastname" runat="server" Text='<%# Bind("Lastname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblage" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sex" SortExpression="Sex">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Sex") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblsex" runat="server" Text='<%# Bind("Sex") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Friendswith" SortExpression="Friendswith">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("Friendswith") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblfriendswith" runat="server" Text='<%# Bind("Friendswith") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount" SortExpression="Amount">
<EditItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("Amount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Bind("Amount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User_Firstname">
<ItemTemplate>
<asp:Label ID="lblfirstname1" runat="server" Text='<%# Bind("Firstname1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User_Middlename">
<ItemTemplate>
<asp:Label ID="lblmiddlename1" runat="server" Text='<%# Bind("Middlename1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User_Lastname">
<ItemTemplate>
<asp:Label ID="lbllastname1" runat="server" Text='<%# Bind("Lastname1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User_ID">
<ItemTemplate>
<asp:Label ID="lblid1" runat="server" Text='<%# Bind("ID1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="YOUR FRIENDS">
<ItemTemplate>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Firstname" SortExpression="Firstname">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Firstname1") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblfirstname2" runat="server" Text='<%# Bind("Firstname1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middlename" SortExpression="Middlename">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Middlename1") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblmiddlename2" runat="server" Text='<%# Bind("Middlename1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lastname" SortExpression="Lastname">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Lastname1") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllastname2" runat="server" Text='<%# Bind("Lastname1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount" SortExpression="Amount">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Amount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblamount2" runat="server" Text='<%# Bind("Amount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Friendswith_gv2">
<ItemTemplate>
<asp:Label ID="lblfriendswith2" runat="server" Text='<%# Bind("Friendswith") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you don't need the duplicate data Use distinct in query.
So your SqlCommand should look like,
SqlCommand cmd = new SqlCommand("SELECT DISTINCT a.*,b.ID,b.Firstname,b.Middlename,b.Lastname,b.Friendswith,b.Amount from [User_TBL_DB] a LEFT OUTER JOIN [Friends_TBL_DB] b ON a.ID=b.Friendswith", conn);
The problem is not your GridView control, the data binded to the GridView is the real issue, since the task of the GridView is just to show data. Performing a LEFT OUTER JOIN you're getting a lot of duplicates. Use the DISTINCT statement to remove duplicates:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT a.*,b.ID,b.Firstname,b.Middlename,b.Lastname,b.Friendswith,b.Amount from [User_TBL_DB] a LEFT OUTER JOIN [Friends_TBL_DB] b ON a.ID=b.Friendswith", conn);

Gridview edit mode for more that one row

I have a Gridview that allows user to edit and delete the records. I am using .net 3.5 using C#.
When I have just one record my edit command is working fine but problem comes when there are more that 1 record in my gridview.
In this case while binding the controls it it is unable to find the controls the second time and thus throws the error.
Here is my code:
protected void gdScheduleNew_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (ViewState["Updating"].Equals(true))
{
TextBox txtactsta = (TextBox)e.Row.FindControl("txtactualstartDate");
TextBox txtactend = (TextBox)e.Row.FindControl("txtactualendDate");
LinkButton lnkUpdate = (LinkButton)e.Row.FindControl("lnkUpdate");
txtactsta.Attributes.Add("ReadOnly", "true");
txtactend.Attributes.Add("ReadOnly", "true");
}
}
}
markup code is:
<asp:GridView ID="gdScheduleNew" runat="server" Width="100%" SelectedIndex="0"
CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333" Height="100px"
OnRowDataBound="gdScheduleNew_RowDataBound" onrowediting="gdSchedule_RowEditing">
<FooterStyle Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Planned Efforts">
<ItemTemplate>
<asp:Label ID="lblscheduleid" runat="server" Text='<%# Bind("scheduleid") %>'
Visible="false"></asp:Label>
<asp:Label ID="lblPlannedEffort" runat="server" Text='<%# Bind("sepcet") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblscheduleid" runat="server" Text='<%# Bind("scheduleid") %>'
Visible="false"></asp:Label>
<asp:TextBox ID="txtsepcet" runat="server" Text='<%# Bind("sepcet") %>'
Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtsepcet" runat="server" Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actual Efforts">
<ItemTemplate>
<asp:Label ID="lblActualEffort" runat="server"
Text='<%# Bind("actualeffort") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtactualeffort" runat="server"
Text='<%# Bind("actualeffort") %>' Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtactualeffort" runat="server" Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned Start Date">
<ItemTemplate>
<asp:Label ID="lblPlannedStart" runat="server"
Text='<%# Bind("plannedstartDate") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtplannedstartDate" runat="server"
Text='<%# Bind("plannedstartDate") %>' class="dateclass" Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtplannedstartDate" runat="server" class="dateclass"
Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned End Date">
<ItemTemplate>
<asp:Label ID="lblPlannedEnd0" runat="server"
Text='<%# Bind("plannedendDate") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtplannedendDate" runat="server"
Text='<%# Bind("plannedendDate") %>' class="dateclass" Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtplannedendDate" runat="server" class="dateclass"
Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actual Start Date">
<ItemTemplate>
<asp:Label ID="lblActualStart" runat="server"
Text='<%# Bind("actualstartDate") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtactualstartDate" runat="server"
Text='<%# Bind("actualstartDate") %>' class="dateclass" Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtactualstartDate" runat="server" class="dateclass"
Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actual End Date">
<ItemTemplate>
<asp:Label ID="lblActualEnd" runat="server"
Text='<%# Bind("actualendDate") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtactualendDate" runat="server"
Text='<%# Bind("actualendDate") %>' class="dateclass" Width="88px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtactualendDate" runat="server" class="dateclass"
Width="88px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Member Name">
<ItemTemplate>
<asp:Label ID="lblMember" runat="server" Text='<%# Bind("membername") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlmem" runat="server" DataTextField="MemberName" DataValueField="MemberID">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="fddlmem" runat="server" DataTextField="MemberName" DataValueField="MemberID">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Bind("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<br />
<asp:LinkButton ID="LnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAddnew" runat="server" CausesValidation="true"
CommandName="AddNew" Text="Submit"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The error is on this line: txtactsta.Attributes.Add("ReadOnly", "true");:
object reference no set to an instance of object
How can I fix this?
Doesn't gdScheduleNew_RowDataBound get called for every row in your gridview? txtactualstartDate and txtactualendDate only exist on edit rows, they do not exist on non editing rows.
Try this:
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)

Categories