How to create gridview updating event dynamically? - c#

public partial class Gridvw_expt2 : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
com = new SqlCommand("Select * from tblExpt",con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows[0] != null)
{
GridView1.AutoGenerateEditButton = true;
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(bc);
}
else
Response.Write("fkj");
}
protected void abc(object sender, GridViewUpdateEventArgs e)
{
Response.Write(e.RowIndex);
}
protected void bc(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = e.NewEditIndex;
}
}
the row used to get in edit mode only if i edit the next row means first row never get in edited mode.Please help why so.

Istead of
GridView1.Attributes.Add("onrowupdating", "abc");
do this:
GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
Also, Instead of
GridView1.Attributes.Add("DataKeyNames", "id");
do this
GridView1.DataKeyNames = new string[] { "id" };
Also x 2, Instead of
if (ds.Tables[0].Rows[0].ToString() != null)
do this
if (ds.Tables[0].Rows[0] != null) //.ToString() will cause an exception if it is actuall null
Why do I feel like I am teaching a class :)

Its because you haven't set up a handler to handle GridView.RowEditing. On your gridview (in the .aspx) you need to wire up a method which will deal with RowEditing.
You're gridview code will look like:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
You need to add:
OnRowEditing="nameOfMethodYouWantToFire"
so it looks like:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="nameOfMethodYouWantToFire">
</asp:GridView>
Where nameOfMethodYouWantToFire is in your code behind (your C#) and it handles the event. Something like this:
protected void nameOfMethodYouWantToFire(object sender, GridViewPageEventArgs e)
{
//Your code here
}

Related

How to add event on buttonfield in a datagridview

I'm currently using ASP.net and C#. I want to add an "Edit" button to my grid view, but I don't know how can I add a command on the button. And I also would gladly welcome any suggestions on how I can enhance this gridview.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null)
{
Response.Redirect("~/LoginPage.aspx");
}
lbl_name.Text = "Welcome :: " + Session["username"];
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT product_name,product_price,product_desc,product_stock FROM product_tbl";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "user_tbl");
GridView1.DataSource = ds.Tables["user_tbl"];
GridView1.DataBind();
}
catch (Exception ex)
{
lbl_result.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
}
You can use RowCommand Event in GridView. The RowCommand Event occurs when a button is clicked in a GridView control. See this
You can add a CommandField with the Edit button:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="GridView1_RowEditing" ...>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowCancelButton="true" />
....
</asp:GridView>
And process the RowEditing event:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ...
GridView1.DataBind();
}
More details are given here: ASP.NET GridView: How to edit and delete data records.

GridView bound to Datatable- Paging does not work properly

I have a webform set up with a button click that parses a .txt file and puts it in a datatable. when the parsing ends the datatable is bound to the gridview. I tried to add paging since I get tons of rows but it does not seem to work properly. Whenever I click on the next page the grid disappears and for it to appear again on the correct page I need to click on the button again.
I tried adding the following code to the source :
<asp:GridView ID="GridView1" Runat="server"
AutoGenerateColumns="true"
AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" >
and this bit :
protected void OnPageIndexChanging(object sender, EventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
but it doesn't seem to change anything. Any idea on what I'm doing wrong?
Try to Add OnPageIndexChanging Event inside GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="5">
and your aspx.cs code. Try to Bind Gridview on Page_Load Event.
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{ this.BindGrid();}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * From [dbo].[your table] "))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//here yo have to assign datasource
//Some thing like this
///GridView1.DataSource=DataTable;
GridView1.DataBind();
}

Dynamically adding multiple rows in data table in C#

I have been tried to use the DATATABLE for storing the values for the entire application. I haven't use any database for storing values permanently. This are the dummy values I could use through out the application.
The issue is actually whenever I add a new row value into my DATATABLE it just overrides the previous values in the DATATABLE instead of adding an new row.
Is there any chance to add multiple rows to the DATATABLE dynamically and I can use it through out the application session.
** MY REGISTER PAGE**
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable;
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
if (!IsPostBack)
{
if (Session["name"] != null)
{
myDataTable = Session["name"] as DataTable;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
myDataTable.Rows.Add(new object []{ TextBox1.Text ,TextBox2.Text,TextBox3.Text , TextBox4.Text,TextBox5.Text ,TextBox6.Text });
HttpContext.Current.Session["name"] = myDataTable;
if (Session["name"] != null)
{
Response.Write("success");
}
}
MY LOGIN PAGE
public partial class login : System.Web.UI.Page
{
DataTable dtResult;
protected void Page_Load(object sender, EventArgs e)
{
dtResult = (DataTable)Session["name"];
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dtResult.Rows.Count; i++)
{
string un = dtResult.Rows[i].Field<string>("username");
string fn = dtResult.Rows[i].Field<string>("password");
if (TextBox1.Text == un && TextBox2.Text == fn)
{
//Response.Write("success");
Response.Redirect("home.aspx");
}
}
}
Issue:
At every Postback you are creating a new datatable and overriding it to the previous:
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
//....
HttpContext.Current.Session["name"] = myDataTable; //overriding to the previous
So when you click on the button to add the new row, it posts back, and recreates a new datatable and then add a new row to that table.
Solution:
You just need to modify the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null) //this is you have to do at every postback
{
myDataTable = Session["name"] as DataTable;
}
if (!IsPostBack)
{
//if it is not post back, create a new DataTable and add values to it
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
}
}

Selecting an item in the RadioButtonList, how to get a list of items to a ListBox from database in asp.net c#

I have a RadioButtonList and a ListBox. I have bound RadioButtonList to database.
Therefore upon selecting an item in the RadioButtonList, I want to retrieve some data into the ListBox. The code I have tried is :
protected void Page_Load(object sender, EventArgs e)
{
RadioFill();
}
public void RadioFill()
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT DISTINCT Param_Name FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
RadioButtonList1.Items.Clear();
RadioButtonList1.DataSource = dset.Tables[0];
RadioButtonList1.DataTextField = dset.Tables[0].Columns["Param_Name"].ColumnName;
RadioButtonList1.DataBind();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT Value_Option FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
ListBox1.Items.Clear();
ListBox1.DataSource = dset.Tables[0];
ListBox1.DataTextField = dset.Tables[0].Columns["Value_Option"].ColumnName;
ListBox1.DataBind();
}
The issue I am facing here is upon selecting an item, the whole panel in which I have placed both my RadioButtonList and ListBox goes invisible.
Kindly help...!! Thankyou...!!
First, change Page_Load method as:
protected void Page_Load(object sender, EventArgs e)ยจ
{
if (!Page.IsPostBack)
{
RadioFill();
}
}
If it not help than post code from your *.aspx file.
Remark: The method RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e),
there is not selecting based on radio button list selected value.

How to Add the CheckBox Field in GridView?

How to add the checkbox field in gridview programatically, what's wrong with my code?
try
{
string Data_source=#"Data Source=A-63A9D4D7E7834\SECOND;";
string Initial_Catalog=#"Initial Catalog=replicate;";
string User=#"User ID=sa;";
string Password=#"Password=two";
string full_con=Data_source+Initial_Catalog+User+Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
DataSet ds2 = new DataSet();
SqlDataAdapter testadaptor = new SqlDataAdapter();
testadaptor.SelectCommand = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
testadaptor.Fill(ds2);
grid1.DataSource = ds2;
CheckBoxField c = new CheckBoxField();
grid1.Columns.Add(c);
grid1.DataBind();
numberofrecords.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception a)
{
Response.Write("Please check ");
Response.Write(a.Message.ToString());
Response.Write(a.Source.ToString());
}//catch
The CheckBoxField will probably want a value for the DataField property. This should match the column names or aliases in your query. (I don't think a checkbox will work with number results, though.)
Edited: didn't realize what you were trying to do. A template field and a regular checkbox should get you closer to what you want. Something like this?
e.g.
const int ColumnSelect = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Get real data here.
DataTable dt = new DataTable();
dt.Columns.Add("count");
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = "5";
GridView1.Columns.Add(new TemplateField());
BoundField b = new BoundField();
GridView1.Columns.Add(b);
b.DataField = "count";
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
}
}
Edit #2: as for getting the value, you can certainly do this. Are you looking for a Javascript or server-side solution? Here's a simple example for server-side if you had a button click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
//Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];
if (cb.Checked)
{
//Do something here.
}
}
}
I had to specify which checkbox object, like this
System.Web.UI.WebControls.CheckBox
Also I had to add this to the gridview aspx page
OnRowDataBound="GridView1_RowDataBound"

Categories