I have made an database application. At the moment i have a add and delete function, but now i am searching for help with the update function. I have searched all over this website for an answer, but no luck i guess. So what i want is that if i click on a record in the ListView that it automatically shows up in the textboxes so that i can change things, and when i click the button "Update" it has to update the record.
Help will be extremely appreciated!
my code of Form1
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=E:\Users\Ali\Documents\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", textBox1.Text);
cmd.Parameters.AddWithValue("#query", textBox2.Text);
cmd.Parameters.AddWithValue("#email", textBox3.Text);
cmd.Parameters.AddWithValue("#subject", textBox4.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown update listview
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
button3.Enabled = true;
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE principalID = #principalID", conn);
cm.Parameters.AddWithValue("#principalID", listView1.SelectedItems[0].Text);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void button2_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
Form2 form2 = new Form2();
form2.Show();
form2.PrincipalID = principalid;
form2.Query = query;
form2.Email = email;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
Why are you using listview.You can use datagridview instead.You can bind the database file with datagridview which would create update,select and insert command itself.
I don't see why you cannot do so. It's relatively easy in listview to update an item.
You need to create EditItemTemplate, for your ListView, so that textboxes appear in your row to be edited.
you can handle this in ItemEditing event.
and then you handle update through ItemUpdating event of ListView.
below am posting a sample example: it might help you out:
create your ListView markup like this:
<asp:ListView ID="lvwTest" runat="server" OnItemDeleting="lvwTest_ItemDeleting" OnItemEditing="lvwTest_ItemEditing"
OnItemUpdating="lvwTest_ItemUpdating">
<LayoutTemplate>
<table>
<tr>
<td>
Column1
</td>
<td>
Column2
</td>
<td>
Column3
</td>
<td>
Action
</td>
</tr>
<tr id="itemplaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lbl1" runat="server" Text='<%#Eval("col1") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("col2") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("col3") %>'></asp:Label>
</td>
<td>
<asp:Button ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="txt1" runat="server" Text='<%#Bind("col1") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt2" runat="server" Text='<%#Bind("col2") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt3" runat="server" Text='<%#Bind("col3") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnUpdate" CommandName="Update" Text="Update" runat="server" />
<asp:Button ID="btnCancel" CommandName="Cancel" Text="Cancel" runat="server" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
so basically you've created EditItemTemplate.
See how ItemTemplate has a button "btnEdit" in the last column and EditItemTemplate has two buttons "btnUpdate" and "btnCancel" instead of that with appropriate CommandName.
now here are your events:
ItemEditing:
protected void lvwTest_ItemEditing(object sender, ListViewEditEventArgs e)
{
lvwTest.EditIndex = e.NewEditIndex;
}
ItemUpdating:
protected void lvwTest_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
TextBox txt = (lvwTest.Items[e.ItemIndex].FindControl("txt1")) as TextBox;
//as above find othe textboxes as well/
//create your update query
//SqlCeCommand cmd = new SqlCeCommand(updateQuery, cn);
//and rest of the syntax
lvwTest.EditIndex = -1;
BindGrid();
}
your datasource:
public void BindGrid()
{
DataTable db = new DataTable();
db.Columns.Add("col1");
db.Columns.Add("col2");
db.Columns.Add("col3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
lvwTest.DataSource = db;
lvwTest.DataBind();
}
inside page's Page_Load
if (!IsPostBack)
BindGrid();
Related
When DataSource Table that bind to GridView containing data . It is easy to load data and add new row to input new data. But when DataSource table is empty, I cannot input new data to GridView because is AddNew command button is not display. How can add new blank row into GridView when Table source is empty to input new data?
My code is working well if datasource table is not blank:
protected void grvEmployeeOnLeave_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlEmpID = (DropDownList)e.Row.FindControl("ddlEmpID");
if (ddlEmpID != null)
{
ddlEmpID.DataSource = EmployeeService.Employee_Working();
ddlEmpID.DataBind();
ddlEmpID.SelectedValue = grvEmployeeOnLeave.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
DropDownList ddlLeaveTypeID = (DropDownList)e.Row.FindControl("ddlLeaveTypeID");
if (ddlLeaveTypeID != null)
{
ddlLeaveTypeID.DataSource = LeaveTypeService.LeaveType_GetByAll2();
ddlLeaveTypeID.SelectedValue = grvEmployeeOnLeave.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlNewEmpID = (DropDownList)e.Row.FindControl("ddlNewEmpID");
ddlNewEmpID.DataSource = EmployeeService.Employee_Working();
ddlNewEmpID.DataBind();
DropDownList ddlNewLeaveTypeID = (DropDownList)e.Row.FindControl("ddlNewLeaveTypeID");
ddlNewLeaveTypeID.DataSource = LeaveTypeService.LeaveType_GetByAll2();
ddlNewLeaveTypeID.DataBind();
e.Row.Cells[6].Text = (grvEmployeeOnLeave.PageIndex + 1) + " of " + grvEmployeeOnLeave.PageCount;
}
}
protected void grvEmployeeOnLeave_OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton delButton = (ImageButton)e.Row.FindControl("lbtDelete");
delButton.Attributes.Add("onclick", "this.originalcolor=this.style.backgroundColor;" + " this.parentNode.parentNode.style.backgroundColor='#f4a396'; if (confirm('Are you sure you want to delete this entry?')) return true; else {this.parentNode.parentNode.style.backgroundColor=this.originalcolor; return false;}");
}
}
protected void grvEmployeeOnLeave_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtNewLeaveDate = (TextBox)grvEmployeeOnLeave.FooterRow.FindControl("txtNewLeaveDate");
TextBox txtNewNotes = (TextBox)grvEmployeeOnLeave.FooterRow.FindControl("txtNewNotes");
DropDownList ddlNewEmpID = (DropDownList)grvEmployeeOnLeave.FooterRow.FindControl("ddlNewEmpID");
DropDownList ddlNewLeaveTypeID = (DropDownList)grvEmployeeOnLeave.FooterRow.FindControl("ddlNewLeaveTypeID");
Data.EmployeeOnLeave obj = new Data.EmployeeOnLeave();
obj.LeaveDate = txtNewLeaveDate.Text;
obj.Notes = txtNewNotes.Text;
obj.EmpID = ddlNewEmpID.SelectedValue;
obj.LeaveTypeID = ddlNewLeaveTypeID.SelectedValue;
EmployeeOnLeaveService.EmployeeOnLeave_Insert(obj);
BindGrid();
}
}
protected void grvEmployeeOnLeave_RowEditing(object sender, GridViewEditEventArgs e)
{
grvEmployeeOnLeave.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grvEmployeeOnLeave_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grvEmployeeOnLeave.EditIndex = -1;
BindGrid();
}
protected void grvEmployeeOnLeave_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtLeaveDate = (TextBox)grvEmployeeOnLeave.Rows[e.RowIndex].FindControl("txtLeaveDate");
DropDownList ddlEmpID = (DropDownList)grvEmployeeOnLeave.Rows[e.RowIndex].FindControl("ddlEmpID");
DropDownList ddlLeaveTypeID = (DropDownList)grvEmployeeOnLeave.Rows[e.RowIndex].FindControl("ddlLeaveTypeID");
TextBox txtNotes = (TextBox)grvEmployeeOnLeave.Rows[e.RowIndex].FindControl("txtNotes");
if (Page.IsValid)
{
Data.EmployeeOnLeave obj = new Data.EmployeeOnLeave();
string Id = grvEmployeeOnLeave.DataKeys[e.RowIndex].Values[0].ToString();
obj.Id = Id;
obj.LeaveDate = txtLeaveDate.Text;
obj.EmpID = ddlEmpID.SelectedValue;
obj.LeaveTypeID = ddlLeaveTypeID.SelectedValue;
obj.Notes = txtNotes.Text;
EmployeeOnLeaveService.EmployeeOnLeave_Update(obj);
}
grvEmployeeOnLeave.EditIndex = -1;
BindGrid();
}
protected void grvEmployeeOnLeave_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Id = grvEmployeeOnLeave.DataKeys[e.RowIndex].Values[0].ToString();
EmployeeOnLeaveService.EmployeeOnLeave_Delete(Id);
BindGrid();
}
When having data:
and when datasource is empty:
I asked and I answer lol :). This is work 100% for whom have problem like me:
Firts create EmpyDataTemplate
..................................
</Columns>
<EmptyDataTemplate>
<table class="table table-striped table-bordered table-hover">
<tr>
<td>Employee Name</td>
<td>Leave Date</td>
<td>Leave Type</td>
<td>Notes</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlNewEmpID" runat="server" DataTextField="EmpName" DataValueField="Id" CssClass="ddl-boxname"> </asp:DropDownList>
</td>
<td>
<asp:TextBox ID="txtNewLeaveDate" runat="server" CssClass="textnumber"></asp:TextBox>
<asp:MaskedEditExtender ID="meetxtNewLeaveDate" runat="server" Mask="99/99/9999" MaskType="Date" OnFocusCssClass="MaskedEditFocus" OnInvalidCssClass="MaskedEditError" TargetControlID="txtNewLeaveDate" Century="2000"/>
<asp:MaskedEditValidator ID="mevtxtNewLeaveDate" runat="server" ControlExtender="meetxtNewLeaveDate" ControlToValidate="txtNewLeaveDate" Display="Dynamic" EmptyValueBlurredText="Date is required" IsValidEmpty="True" InvalidValueBlurredMessage="Date format is invalid" SetFocusOnError="True"/>
</td>
<td>
<asp:DropDownList ID="ddlNewLeaveTypeID" runat="server" DataTextField="LeaveTypeName" DataValueField="Id" CssClass="form-control"> </asp:DropDownList>
</td>
<td>
<asp:TextBox ID="txtNewNotes" runat="server" CssClass="textnumber"></asp:TextBox>
</td>
<td>
<asp:ImageButton ID="lbtAddNew" runat="server" ToolTip="Add New" ImageUrl="/App_Themes/Admin/img/file_add.png" CausesValidation="False" OnClick="AddNew_Click" />
</td>
</tr>
</table>
</EmptyDataTemplate>
<FooterStyle CssClass="Control" />
<pagerstyle ForeColor="black"
HorizontalAlign="Center"></pagerstyle>
</asp:GridView>
then:
protected void AddNew_Click(object sender, EventArgs e)
{
DropDownList ddlNewEmpID = grvEmployeeOnLeave.Controls[0].Controls[0].FindControl("ddlNewEmpID") as DropDownList;
DropDownList ddlNewLeaveTypeID = grvEmployeeOnLeave.Controls[0].Controls[0].FindControl("ddlNewLeaveTypeID") as DropDownList;
TextBox txtNewLeaveDate = grvEmployeeOnLeave.Controls[0].Controls[0].FindControl("txtNewLeaveDate") as TextBox;
TextBox txtNewNotes = grvEmployeeOnLeave.Controls[0].Controls[0].FindControl("txtNewNotes") as TextBox;
Data.EmployeeOnLeave obj = new Data.EmployeeOnLeave();
obj.LeaveDate = txtNewLeaveDate.Text;
obj.Notes = txtNewNotes.Text;
obj.EmpID = ddlNewEmpID.SelectedValue;
obj.LeaveTypeID = ddlNewLeaveTypeID.SelectedValue;
EmployeeOnLeaveService.EmployeeOnLeave_Insert(obj);
BindGrid();
}
then:
protected void grvEmployeeOnLeave_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
DropDownList ddlNewEmpID = (DropDownList)e.Row.FindControl("ddlNewEmpID");
ddlNewEmpID.DataSource = EmployeeService.Employee_Working();
ddlNewEmpID.DataBind();
DropDownList ddlNewLeaveTypeID = (DropDownList)e.Row.FindControl("ddlNewLeaveTypeID");
ddlNewLeaveTypeID.DataSource = LeaveTypeService.LeaveType_GetByAll2();
ddlNewLeaveTypeID.DataBind();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{...................................................
}
It works perfectly.
While binding Gridview control, you can check if any row exist in datatable, else you can add default row as "No data".
By this you can get one defualt record into your Gridview, so from your footer to can add new records
if (dt.Rows.Count == 0)
{
DataRow drow = dt.NewRow();
drow[0] = "No data";
dt.Rows.Add(drow);
}
grvEmployeeOnLeave.DataSource = dt;
grvEmployeeOnLeave.DataBind();
I'm having trouble returning to listview and cancelling the edit of items using ASP and C#.
I already have the same answer as this
but I'm still getting the error message of Cancel can only be called from the currently-edited record or an insert item.
Here is the offending code - any pointers on what is causing this would be very useful:
I also have a layout, selected template, and insert which are all identical.
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqlDatasource1"
EnableViewState="true" DataKeyNames="EndUserId" AllowPaging="True"
OnItemCommand="ListView1_ItemCommand" OnItemCanceling="ListView1_ItemCanceling">
<EditItemTemplate>
<tr>
<asp:Label runat="server" ID="tbId" Text='<%#Eval("EndUserId") %>' Visible="false" />
<td>
<asp:TextBox runat="server" ID="tbEmail" Text='<%#Eval("Email") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="tbRole" Text='<%#Eval("Role") %>' />
</td>
<td>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
c# backend controlling
protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
ListView1.EditIndex = -1;
ListView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
if (!IsPostBack)
{
}
}
added backend
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Label tbId = (Label)e.Item.FindControl("tbId");
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string updateCommand =
"UPDATE [EndUser_tbl] SET [Email]='" +
tbEmail.Text + "', [Password]='" + tbPass.Text +
"'WHERE EndUserId=" + Convert.ToInt32(tbId.Text) + ";";
sqlDatasource1.UpdateCommand = updateCommand;
}
if (e.CommandName == "Delete")
{
Label id = (Label)e.Item.FindControl("tbId");
string deleteCommand = "DELETE FROM [EndUser_tbl] " +
"WHERE EndUserId=" + Convert.ToInt32(id.Text);
sqlDatasource1.DeleteCommand = deleteCommand;
}
if (e.CommandName == "Insert")
{
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string insertCommand = "INSERT INTO [EndUser_tbl] " +
"([Email],[Password],[ContractRef],[Role])" +
"VALUES ('" + tbEmail.Text + "','" + tbPass.Text +
"','" + tbPass.Text + "');";
sqlDatasource1.InsertCommand = insertCommand;
}
}
Change the Page_load like this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
}
}
And try it again.
I bind the values in usercontrol dropdownlist
But when I add the usercontrol row that time values are not binded in dropdownlist
Code:
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TimesheetUserControl.ascx.cs" Inherits="Portal.TimesheetUserControl" %>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownActivities" Width="150px" runat="server"></asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</td>
</tr>
.aspx
<uc:Timesheet ID="Timesheet" runat="server" />
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
BindActivities();
}
}
protected void BindActivities()
{
DropDownList dropActivities = Timesheet.FindControl("DropDownActivities") as DropDownList;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (IsPostBack)
{
GenerateControls();
}
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
TimesheetUserControl ctrl = (TimesheetUserControl)Page.LoadControl("TimesheetUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
Button thisButton = (Button)sender;
List<string> temp = null;
var uc = (TimesheetUserControl)this.LoadControl(#"TimesheetUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if Click add button rows are added but in second values are not binded in dropdownlist
Any ideas? Thanks in advance.
find the user controls by the id you given and then you can find the DropDownList inside the usercontrol.
protected void BindActivities()
{
foreach (string controlName in NoOfControls)
{
TimesheetUserControl userControl = Timesheet.FindControl(controlName) as TimesheetUserControl;
if(userControl == null) return;
DropDownList dropActivities = userControl.FindControl("DropDownActivities") as DropDownList;
if(dropActivities == null) return;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
I am try to toggle the display subnet data(childList). This codes below are working fine, but not able to toogle the display. When I click on the (+) sign, the ChildList dataList expands and displays the list subset data (Contact). However, I want to change the (+) to (-) when childList data expanded. And when user clicks on (-), it will collapse back (the child list disappear)
Any idea how to do this? an example code would be great since I am a newbie of ASP.NET.
<table width="595px">
<asp:DataList BackColor="#ffffff" id="DataList1" DataSourceID="dsCompanyList" runat="server" Width="100%" DataKeyField="Company">
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" Text="+" CommandArgument='<%#Container.ItemIndex%>'
OnCommand="LinkButton1_Command"
></asp:LinkButton>
</td>
<td><%#Eval("Row")%></td>
<td><%#Eval("Company")%></td>
</tr>
<asp:Panel ID="pnlChildView" runat="server">
<asp:DataList ID="childList" runat="server" Width="100%">
<ItemTemplate>
<tr>
<td><%#Eval("FirstName")%></td>
<td><%#Eval("LastName")%></td>
</tr>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</table>
Code Behind:
public partial class _CompanyList2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
//pass index of item in command argument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//depending on your needs bind the details on demand
//or preload during ItemDataBound
Panel childViewPanel = (Panel)DataList1.Items[itemIndex].FindControl("pnlChildView");
if (childViewPanel != null)
{
//toggle visibility of childViewPanel and bind child list if panel is visible
DataList childList = (DataList)childViewPanel.FindControl("childList");
if (childList != null)
{
//int keyValue = (int)DataList1.DataKeys[itemIndex];
string keyValue = (string)DataList1.DataKeys[itemIndex];
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connApps"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT FirstName, LastName FROM dbo.Import_CompanyContact WHERE REPLACE(Company, '''', '') = '" + keyValue + "'", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader())
{
childList.DataSource = dr;
childList.DataBind();
}
}
}
}
}
}
}
I have Template Field for gridview as below:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
When i am in gv_RowUpdating event, i wanted to take the value of edited field by findcontrol.
For that i am using following code:
`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
But each time it is showing me null value in txtUname when i debug the code.
What can be the problem?
Full Event Code:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=#eName");
cmd.parameters.AddParametersWithValue("#eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
EDIT
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
refer this
http://www.codeproject.com/Articles/37207/Editable-Gridview-with-Textbox-CheckBox-Radio-Butt
also put your code for Edit command. it might be RowEditing or RowCommand