I have a web part, in the createchildcontrols function it creates a gridview, calls a stored procedure and populates the grid view. One column of the gridView is a command field that has the key value for an item & is passed to another web part on the page to show the details. All was working fine until they wanted me to add a search capability to the list web part.
At first this appeared to work, the data in the columns sems to reflect correct search results, but the command field retains the orginal values when the page was first loaded with no search criteria.
Also, when doing the search it appears that it goes through the createchildcontrols function, populates gridview with all of the items, then runs through the code in the btnSearch_Click where more sql is run with the specific search criteria and the gridview
is re-bound with the search results (but orginal key values in command field).
Any ideas on how I've messed this up?
Code from CreateChildControls:
_view = new GridView();
this.Controls.Add(this._view);
_view.Caption = "Rate Quote Email";
_view.AutoGenerateColumns = true;
_view.DataKeyNames = new string[] { "XREF_ID" };
CommandField field = new CommandField();
_view.SelectedRowStyle.BackColor = Color.Red;
field.ShowSelectButton = true;
field.ButtonType = ButtonType.Link;
_view.Columns.Add(field);
_view.AllowPaging = true;
_view.PageSize = 20;
_view.AlternatingRowStyle.BackColor = Color.Cornsilk;
_view.PageIndexChanging += new GridViewPageEventHandler(_view_PageIndexChanging);
Code from btnSearch_Click:
DataSet ds = new DataSet();
rdr = cmd.ExecuteReader();
ds.Clear();
_view.DataSource = null;
ds.Load(rdr, LoadOption.PreserveChanges, "");
rdr.Close();
rdr.Dispose();
_view.DataSource = ds.Tables[0];
_view.DataBind();
DataSet ds = new DataSet();
ds.Clear();
rdr = cmd.ExecuteReader();
ds.Load(rdr, LoadOption.PreserChanges, "");
rdr.Close();
rdr.Dispose();
_view.DataSource = null;
_view.DataSource = ds.Tables[0];
_view.DataBind();
ds.Dispose();
cmd.Dispose();
conn.Dispose();
Related
I doing a web page in asp.net and in a module have select a Excel archive with FileUpLoad and click in a button import. Hitherto I'm fine. But in the moment than I want select other Excel archive and click in the button import, don't clear the GridView and show error. I attempt with this because I see in other questions similar to this.
With this I load the Grid
Conn = string.Format(Conn, DireccionArchivo, MostrarHDR);
OleDbConnection ConnExcel = new OleDbConnection(Conn);
OleDbCommand CmdExcel = new OleDbCommand();
OleDbDataAdapter Oda = new OleDbDataAdapter();
DataTable Dt = new DataTable();
CmdExcel.Connection = ConnExcel;
ConnExcel.Open();
CmdExcel.CommandText = "SELECT * From ["Page1$"]";
Oda.SelectCommand = CmdExcel;
Oda.Fill(Dt);
ConnExcel.Close();
grdResultados.Caption = Path.GetFileName(DireccionArchivo);
grdResultados.DataSource = Dt;
grdResultados.DataBind();
And with this I want to clear the GridView and last y called of new the method of load the GridView
DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;
grdResultados.DataBind();
The error than show me is in the grdResultados.DataBind(); when called the second time.
Just use null value:
grdResultados.DataSource = null;
grdResultados.DataBind();
I resolved the problem, in the moment than clear the GridView with
DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;
grdResultados.DataBind();
this clear the GridView but dont clear the names of columns, and this was the error, also have to clean the names of the columns. To remove the columns:
for (int i = 0; grdResultados.Columns.Count > i; )
{
grdResultados.Columns.RemoveAt(i);
}
and in the method of load th GridView must be generate the columns automatically with this property:
grdResultados.AutoGenerateColumns = true;
I leave this in case anyone else has the same problem
try this
grdResultados.DataSource = null;
or
grdResultados.Rows.Clear();
then rebind the gridview
int gvHasRows = grdResultados.Rows.Count;
if (gvHasRows > 0)
{
grdResultados.Columns.Clear();
grdResultados.DataBind();
}
First check that there is data in the Gridview before trying to clear.
Rows has no Clear function.
If you use a Session clear the session Example:
DataTable ds = new DataTable();
ds = null;
GV.DataSource = ds;
GV.DataBind();
for (int i = 0; GV.Columns.Count > i; )
{
GV.Columns.RemoveAt(i);
}
ViewState["CurrentData"] = null;
Make an empty data table with just your column names and re bind
You can simply do this:
GridView1.SelectedIndex = -1;
If dataset IsNot Nothing AndAlso dataset.Tables.Count > 0 AndAlso dataset.Tables(0).Rows.Count > 0 Then
grid.DataSource = dataset
grid.DataBind()
Else
grid.DataSource = Nothing
grid.DataBind()
If you're using a XAML defined Grid, use this instead:
GridView1.Children.Clear();
GridView1.RowDefinitions.Clear();
GridView1.ColumnDefinitions.Clear();
I have an Access database with pictures and other data stored. I want to show the picture from the database in a DatagridView.
This works but the image height is very small in the DatagridView. I also want to stretch the image.
How do I do this ?
Here is where I bind the data from the Access database to the datagridview:
conn.Open();
OleDbCommand cmd = new OleDbCommand(cmdstr, conn);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
DatagridView1.DataSource = table;
conn.Close();
With this code I created a column to show the picture, but I can't bind the data from the database to this column.
DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
photoColumn.DataPropertyName = "Photo";
photoColumn.Width = 200;
photoColumn.HeaderText = "Image";
photoColumn.ReadOnly = true;
photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
DatagridView1.Columns.Add(photoColumn);
The data of your database are bind by the fist code segment you have written, speciffically:
DatagridView1.DataSource = table;
binds the data brought by your query to your Datagridview. All you have to do is to set up the query accordingly to retrieve the image.
Franlky with Dataadapter I am not quite sure how to store an image but if you use Sqlreader:
...
if (reader.HasRows)
{
while (reader.Read())
{
string s1 = reader[0].ToString(); ///1st field you are interested
string s2 = reader[1].ToString(); //2nd field you want
byte[] img = (byte[])(reader[2]); //your photo image
}
}
Finally be sure, to set on the designer AutogenerateColumns property to true for your Datagrid.
In my grid view i wants to insert new records to the last row of grid view. so i set Gridview2.Allowsorting is false. but it doesn't works on my grid view. my code is here
public void gridview2_selectgroup()
{
if (Session["selectedgroupes"] != null)
{
ArrayList groups = new ArrayList();
ArrayList student_id_list = new ArrayList();
groups = (ArrayList)Session["selectedgroupes"];
student_id_list=(ArrayList)Session["STUDENT_ID"];
string select_string="SELECT student_name,student_id,student_nric,student_group FROM student_details WHERE student_group='"+groups[0].ToString().Trim()+"' ";
for(int i=1;i<groups.Count;i++)
{
select_string+= " or student_group='"+groups[i].ToString().Trim()+"'";
}
if(Session["STUDENT_ID"]!=null)
{
for(int i=0;i<student_id_list.Count;i++)
{
select_string+= " or student_id='"+student_id_list[i].ToString().Trim()+"'";
}
}
SqlConnection con = obj.getcon();
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(select_string, con);
adapter.Fill(ds);
GridView2.DataSource = ds;
GridView2.AllowSorting = false;
GridView2.DataBind();
con.Close();
}
what will be the reason? It works on another grid views on my project . please help
Click on your gridview in .aspx page and hit f4. The properties window will popup. There u check the 5th line (Allow Sorting).If its true make it false. Sometimes the codebehind code will not work due to timings.If its already false then place your "GridView2.AllowSorting = false;" in between datasource and databind.
GridView2.DataSource = ds;
GridView2.AllowSorting = false;
GridView2.DataBind();
try this
string select_string="SELECT student_id,student_name,student_nric,student_group FROM student_details WHERE student_group='"+groups[0].ToString().Trim()+"' ";
I am trying to get one column from my datatable to be displayed as a combo box in my grid view. Also need to have the ability to fill the combo with a small collection to chose from. It will not show the values when i bind it from the Gui so I am trying it programmatic but cant seem to find the right code.
connection2 = new MySqlConnection(ConnectionString2);
try
{
string proid = txtbxProjId.Text;
//prepare query to get all records from items table
string query2 = "select sl.sample_id As sample_id, sl.sample_number As Sample_Number, sl.sample_date As Sample_Date, sl.sample_time As Sample_Time, sl.sample_comments As Sample_Comments FROM spt_sample_login sl Where project_id = '"+proid+"'";
//prepare adapter to run query
adapter2 = new MySqlDataAdapter(query2, connection2);
adapter3 = new MySqlDataAdapter(query2, connection2);
//create a DataTable to hold the query results
DataTable dTable2 = new DataTable();
DataSet DS2 = new DataSet();
//fill the DataTable
//get query results in dataset
adapter2.Fill(dTable2);
adapter3.Fill(DS2);
//return datatable with all records
//BindingSource to sync DataTable and DataGridView
//set the BindingSource DataSource
GridView1.DataSource = dTable2;
this.GridView1.Columns["sample_id"].Visible = false;
this.GridView1.Columns["Sample_Type"].DisplayIndex = 4;
this.GridView1.Columns["Sample_Type"].Visible = true;
//set the DataGridView DataSource
}
catch (MySqlException ex)
{
}
}
This works but shows the Sample_Type as a text box where i want it to be a combo with F,P Q,B as options.
Thank you
Brent
You have to put your ComboBox in a itemTemplate, and you have to fill it during rowDataBound event.
Quick exemple from my current project:
DropDownList ddlRole = (DropDownList)e.Row.FindControl("ddlRole");
ddlRole.DataSource = GetTruckersRoles();
string[] rolesList = Roles.GetRolesForUser((string)gvTruckers.DataKeys[e.Row.RowIndex][0]);
if (rolesList.Length > 0)
{
//If user is not in any roles, dont' do this
ddlRole.SelectedValue = rolesList[0];
}
ddlRole.DataBind();
Just adapt the code to your situation
all. I'm having a problem getting the GridView.AutoGenerateEditButton property to do anything for me. Right now, I set it to true, and I don't even get the button added to my GridView, so obviously I can't even get any further to code the actual events. Here is what I have so far (sorry for the messy code; I'm getting close to my deadline and it's been a bit frantic):
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
using(SqlDataReader dr = cmd.ExecuteReader())
{
DataSet ds1 = new DataSet();
DataTable dt1 = ds1.Tables.Add("Specs 1");
if (dt1.Rows.Count == 0)
{
ds1.Tables["Specs 1"].Columns.Add("General Information");
ds1.Tables["Specs 1"].Columns.Add("Customer Name");
ds1.Tables["Specs 1"].Columns.Add("Address");
// etc.
}
while (dr.Read())
{
DataRow newRow = ds1.Tables["Specs 1"].NewRow();
int x = 0;
foreach (DataColumn thisColumn in ds1.Tables["Specs 1"].Columns)
{
newRow[ds1.Tables["Specs 1"].Columns[x]] = Convert.ToString(dr[x]);
x += 1;
}
ds1.Tables["Specs 1"].Rows.Add(newRow);
}
DataSet flipped_ds1 = FlipDataSet(ds1); // Flips the dataset's orientation.
Then, when it's time for me to add the GridView to the page, I use the following code:
GridView outputGrid1 = new GridView();
outputGrid1.ShowHeader = false; // Remove the integer headings.
outputGrid1.DataSource = flipped_ds1;
outputGrid1.DataBind();
outputGrid1.AutoGenerateEditButton = true;
Controls.Add(outputGrid1);
Now, the columns are being added exactly the way that I want, and the data is populating properly. However, I don't have the edit buttons that I assume I should have by setting the GridView.AutoGenerateEditButton property to true. I'm sure I'm missing something simple; can someone help? Thanks very much.
Have you tried setting the AutoGenerateEditButton before the call to DataBind() ? Is there a way to prevent updates in your DataSet (the introspection may detect it and avoid providing a useless button maybe) ?