How to enable all textbox controls in itemtemplate of Repeater by itemCommand? - c#

I have a repeater and I used label for display and a hidden text box which holds the same value. Now I want to enable the text box so that the user can edit inputs in the table/repeater. Can anyone help me? below is my code
public void FillTable()
{
DataTable table = new DataTable();
using (MySqlConnection conn = Functions.GetConnection())
{
string sql = "SELECT FirstName, LastName from tbluser LIMIT 15";
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(table);
conn.Close();
}
}
asd.DataSource = table;
asd.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
asd.Visible = true;
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
Literal lblname = (Literal)item.FindControl("Label2");
TextBox txtbox = (TextBox)item.FindControl("Label3");
if (e.CommandName == "EDIT")
{
lblname.Visible = false;
txtbox.Visible = true;

You are not getting the textbox but the label twice:
TextBox txtbox = (TextBox)item.FindControl("Label3");

Related

Asp.Net finding in Code-behind edited values in GridView with autogenerated columns

I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

update button on nested gridview asp.net c#

I have this nested grid view in which the data are shown in textboxes and i also have an update button but when i click the button instead of updating the data on the data table it just updates the new value on the grid view itself and shows it along with the old value and i don't get any error though. Please help me thanks.
the code:
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
using (OleDbConnection con = new OleDbConnection(strConnString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandText = query;
using (OleDbDataAdapter sda = new OleDbDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = gvSDate.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvSDate2 = e.Row.FindControl("gvSDate2") as GridView;
gvSDate2.DataSource = GetData(string.Format("select ID, Function, FunctionDate, FunctionTime, CelebrateName from function where ID={0}", ID));
gvSDate2.DataBind();
}
}
protected void gvSDate2_RowDataBound(object sender, GridViewRowEventArgs f)
{
if (f.Row.RowType == DataControlRowType.DataRow)
{
GridView gvSDate2 = f.Row.FindControl("gvSDate2") as GridView;
TextBox textFunction = f.Row.FindControl("textFunction") as TextBox;
TextBox textFunctionDate = f.Row.FindControl("textFunctionDate") as TextBox;
TextBox textFunctionTime = f.Row.FindControl("textFunctionTime") as TextBox;
TextBox textCelebrateName = f.Row.FindControl("textCelebrateName") as TextBox;
Label lblID = f.Row.FindControl("lblID") as Label;
Button update1 = f.Row.FindControl("update1") as Button;
string Function = textFunction.Text;
string FunctionDate = textFunctionDate.Text;
string FunctionTime = textFunctionTime.Text;
string CelebrateName = textCelebrateName.Text;
string ID1 = lblID.Text;
update1.Click += (send, g) =>
{
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string updateQuery = "UPDATE function SET Function=#Function, FunctionDate=#FunctionDate, FunctionTime=#FunctionTime, CelebrateName=#CelebrateName WHERE ID=#ID";
command.CommandType = CommandType.Text;
command.CommandText = updateQuery;
command.Parameters.AddWithValue("#ID", ID1);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#CelebrateName", CelebrateName);
};
}
}

Populate gridview from dropdown control (C#)

I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();

how to display value in listbox from dataview

i have a textbox and listbox in a winform app. when i type a value(i.e,string) in the textbox i want the listbox to show the values from datatable and when i am selecting a particular value from listbox it will display in textbox .
code:
private void txtIName_TextChanged(object sender, EventArgs e)
{
string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (dt = new DataTable())
{
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
listBox1.DataSource = dv;
}
}
}
}
}
but i got the output in listbox like "system.data.datarow". By debugging i can seen that rows which i want, in dataview 'dv'. what i am missing here? thanks.
You don't need to load data each time the TextChanged event fires. It's enough to load data in Load event of your form and then in TextChanged just filter the data. Then using an event like DoubleClick of ListBox set the text of TextBox:
private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string constring = #"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin#123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
{
sda.Fill(dataTable);
}
}
this.listBox1.DataSource = new DataView(dataTable);
this.listBox1.DisplayMember = "IName";
this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
var dv = (DataView)this.listBox1.DataSource;
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var item = (DataRowView)listBox1.SelectedItem;
if (item != null)
this.txtIName.Text = item["IName"].ToString();
else
this.txtIName.Text = "";
this.listBox1.Visible = false;
}
Don't forget to attach Form1_Load, txtIName_TextChanged and listBox1_DoubleClick handlers to events.
You must specify your DisplayMember, it must be some Field in your DataView
listBox1.DisplayMember = "Your Field"
then you can suscribe to the event SelectedValueChanged :
listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
visual studio create for you an event handler
void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
// you get your selected item here
}
hope it helps

Categories