asp.net gridview template column - asp.net

In my asp.net gridview, I am placing a template column which displays an image.
Inside the template column I added an image control, and it successfully displaying the images from the database. I am also using paging.
Paging also happening but when I do paging images are not coming in the gridview in proper order for example first three pages it diplays suppose a.jpg, b.jpg,c.jpg and when I click on page number it repeats the same picture instead of remaining pictures, i am using if(!ispostback) in the load event also. please help me out.
my code in page load event is:
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
path = Server.MapPath(#"~\images");
if (!IsPostBack)
{
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
}
and my code in paging event is
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
thank in advance
sangita

When you write your paging method you still need to re-query the datasource and rebind your gridview (along with setting the PageIndex).

assuming that you have only the image name stored in the database you can do this in the Image Control in you template column
set the databinding for the image url as
String.Format("images/{0}",Eval("photo"))
and as boon has said
When you write your paging method you
still need to re-query the datasource
and rebind your gridview (along with
setting the PageIndex).
you can declare a method that fetches the records from the database as
protected void fillData()
{
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and use it to bind data to your gridview
and in your paging_indexChanging function
GridView1.PageIndex = e.NewPageIndex;
fillData();

Please verify the image paths in pagination. If the images paths are same, then disable the browser cache.

Related

store selected grid view value into database

I've a gridview in which a radiobutton is used to select a particular row of data. Now I need to save radio button selected row into database. How do I achieve this? I'm not using JQuery or Ajax, my entire coding is done on ASP.NET
I didn't got your problem correctly,But the ideal methodology is to use Check box instead of Radio button will be far better for your coding purpose.
The below code is a demo for inserting the values into the database from a grid view where in the particular rows will be inserted which has been checked.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionstring"].ToString());
SqlCommand cmd = new SqlCommand();
string active = "N";
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string A = GridView1.Rows[i].Cells[0].Text;
string B = GridView1.Rows[i].Cells[1].Text;
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBox1");
if (Ckbox.Checked == true)
{
cn.Open();
cmd.CommandText = "Insert into table_name(A,B) values (#A,#B)";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#A", A);
cmd.Parameters.AddWithValue("#B", B);
cmd.ExecuteNonQuery();
cn.Close();
}
}
Hope this will be helpful for you.
Easy
Search through GridRows
FindControl radio button on each row.
Check that button is Checked or not.
and now try it.

Add New Rows to GridView

I have a GridView on my page and on a button_OnClick event I'm wanting to add a new row to the grid.
I can add a row to the table using the following code, which works fine, but as I'm binding the DataTable to the grid any previous entries are lost.
string selectedProduct= ddlProducts.SelectedItem.Text;
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
So whilst I understand why this is causing the data loss, I'm not really sure how to get around it.
How can I add a new row to the GridView on each button click whilst retaining the previously added row? The data is not stored anywhere other than the grid itself, so there is no real datasource.
There are options such as Add row to gridview on client side which uses Jquery, but I have read that it isn't a great idea to use that when adding / removing items from the grid. Perhaps that is wrong? Or there is this Add new row to gridview but there isn't much detail there.
You need to store the Products into ViewState (or SessionState or Database) so that it can persist on post back.
For example,
private DataTable ProductDataTable
{
get { return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
protected void AddRowButton_Click(object sender, EventArgs e)
{
string selectedProduct = ddlProducts.SelectedItem.Text;
// Get the data from ViewState
DataTable dataTable = ProductDataTable;
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
// Save the data back to ViewState
ProductDataTable = dataTable;
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
Here is a sample you can try:
DataTable dt = new DataTable(); 
if (ViewState["CurrentTable"]!=null)
{
dt = (DataTable)ViewState["CurrentTable"];
  }
else
{
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
}
DataRow dr = null;            
dr = dt.NewRow();
dr["Col1"] = "tes";      
dr["Col2"] = "test";
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt; 
GridView1.DataSource = dt; 
GridView1.DataBind();
Sorry for bad formatting, typed this with my cellphone. Hope it helps! :-)
// OnButten click
function addrow(sender, args) {
// td add as per your column required
$("#GridView1 tbody").append('<tr><td>00001</td><td>Mr.</td><td>LOKESH N</td></tr>');
}

Grid view binded with a text box unable to show results

i'm trying to bind a search textBox ( that uses a Stored Procedure ) with a grid view but when ever i run them and type the search condition ,no results are displayed and the GridView it self dosent show . i tried many ways including using a DataAdapter & DataSet to fill the results of the search textBox and then bind the DataSet to the GridView. but it didnt work either here is the code:
protected void SearchButton_Click(object sender, EventArgs e)
try
{
string con_str = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(con_str);
SqlCommand com = new SqlCommand("dbo.SearchRecords", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter pDocumentTitle = new SqlParameter("#Doc_Title", SearchTextBox.Text);
SqlParameter pUserID = new SqlParameter("#User_ID", SearchTextBox.Text);
SqlParameter pDocumentType = new SqlParameter("#Doc_Type", SearchTextBox.Text);
SqlParameter pDocumentDescription = new SqlParameter("#Doc_Description",SearchTextBox.Text);
com.Parameters.Add(pDocumentTitle);
com.Parameters.Add(pUserID);
com.Parameters.Add(pDocumentType);
com.Parameters.Add(pDocumentDescription);
con.Open();
SqlDataAdapter DA = new SqlDataAdapter(com);
com.ExecuteNonQuery();
DataSet t = new DataSet();
DA.Fill(t);
GridView1.DataBind();
GridView1.DataSource = t;
}
catch (Exception ex)
{
Label2.Text = ex.Message;
//throw;
}
}
I could be wrong but don't you need to call DataBind() after you have set the DataSource property? e.g.
GridView1.DataSource = t;
GridView1.DataBind();
You should change the order of binding as follow...Always write DataBind() after assigning the DataSource to Any DataControl
GridView1.DataSource = t;
GridView1.DataBind();
datasource must define first ,then do the binding
GridView1.DataSource = t;
GridView1.DataBind();

Error with the event handlers of dynamic linkbutton

I am retrieving data from database depending upon the texboxes input and storing in a datatable , after then from datatable im sending data into dynamic table and displaying table in a panel,in the table all the data of the first column are of linkbuttons, i wrote event handler for dynamic link buttons , but the event handler is not triggering, and i want to store the linkbutton text in a string in the event handler, but the event handler is not triggering.
Code:
protected void Button1_Click(object sender, EventArgs e)
{
// GridView1.
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(str);
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select ID,title,desc from [SO] where ID='" + TextBox1.Text.ToString() + "'or title='" + TextBox2.Text.ToString() + "'";
OleDbDataAdapter db = new OleDbDataAdapter(cmd);
db.Fill(dt);
Table tb = new Table();
tb.BorderColor = Color.Black;
tb.BorderWidth = 2;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
TableRow tr = new TableRow();
tr.BorderColor = Color.Black;
tr.BorderWidth = 2;
tr.ID = "tr" + i;
TableCell tc = new TableCell();
tc.BorderColor = Color.Black;
tc.BorderWidth = 2;
tc.ID = "tc" + i;
TableCell tc1 = new TableCell();
tc1.BorderColor = Color.Black;
tc1.BorderWidth = 2;
tc1.ID = "tc1" + i;
TableCell tc2 = new TableCell();
tc2.BorderColor = Color.Black;
tc2.BorderWidth = 2;
tc2.ID = "tc2" + i;
LinkButton t = new LinkButton();
t.BorderColor = Color.Black;
t.BorderWidth = 2;
t.ID = "t" + i;
t.Click += new EventHandler(t_edit);
TextBox t1 = new TextBox();
t1.BorderColor = Color.Black;
t1.BorderWidth = 2;
t1.ID = "t1" + i;
TextBox t2 = new TextBox();
t2.BorderColor = Color.Black;
t2.BorderWidth = 2;
t2.ID = "t2" + i;
dr = dt.Rows[i];
t.Text = Convert.ToString(dr["ID"]);
t1.Text = Convert.ToString(dr["title"]);
t2.Text = Convert.ToString(dr["desc"]);
tc.Controls.Add(t);
tc1.Controls.Add(t1);
tc2.Controls.Add(t2);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tb.Rows.Add(tr);
}
Panel1.Controls.Add(tb);
}
protected void t_edit(object sender, EventArgs e)
{
}
k but by using the sessions concept im retrieving the total table so that the linkbuttons are also retrieving , and i want to add the linkbttons on a button click , here the problem is the eventhandler is not assiging to the linkbutton, and im adding linkbuttons on button click,not on page load.
You must have to use Page_Init or Page_Load event handler to write code that create controls dynamically. Please read MSDN pages on How to add controls dynamically and ASP.NET Page life cycle articles.
You can add event handlers to the Page_Load event but the important think to remember is that they must be added on every page load. It is common to do setup type tasks such as this in a !Page.IsPostBack clause. When wiring up event handlers that's not the case otherwise they will seem to disappear
if(!Page.PostBack)
{
control.EventRaised += new EventHandler(EventResponse)
}
is wrong and will result in the handler disappearing on postback

I want to display the mysql table's contents into gridview

what can I do when my all database table's name into dropdown list & when i select or click the table name from dropdown list display the whole field into the gridview dynamically..please give me best solution in asp.net.
Use the mysql commands SHOW TABLES and DESCRIBE table_name and draw the result into grids. I don't know the ASP codes.
(This is an example for MSSQL db. For mysql you can try using OdbcConnection or OleDbConnection depending on MySql version.)
1.Here is direct way to select data:
public class DAL
{
public static DataTable GetTableData(string tableName)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(Settings.Default.ConnectionString))
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = string.Format("select * from {0}", tableName);
using (SqlDataReader rd = cmd.ExecuteReader())
{
bool ColumnsAdded = false;
while (rd.Read())
{
if (!ColumnsAdded)
{
for (int i = 0; i < rd.FieldCount; i++)
dt.Columns.Add(rd.GetName(i), rd.GetFieldType(i));
}
DataRow row = dt.NewRow();
for (int i = 0; i < rd.FieldCount; i++)
row[i] = rd[i];
dt.Rows.Add(row);
ColumnsAdded = true;
}
}
}
return dt;
}
}
2.Next you drop ObjectDataSource onto your form with a GridView (setting its DataSourceID to objectdatasource). Specify this method on your ObjectDataSource select method. You can specify parameter for tableName to be read from Control (DropDownList1 for instance). DropDownList1 presumebly keeps a list of tables.
You can dynamically load the table contents into gridview by putting a select query for the table and then bind that dataset to gridview datasource.
Hope this helps you!!

Resources