i have a GridView,
<asp:GridView ID="managerList" runat="server" DataSourceID="SqlDataSource2">
in the code behind,
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
when i load the page, it works fine, the paging works fine, too.
Then i want to get the subset of the list by click on a search button:
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
managerList.DataBind();
}
it works fine, give me the subset of the list.
However, when i click on "next page", it gives me the whole list, page #2. I know it's because it sends a postback, and it bind the original select command. But how can i do to give me the subset of the list when i click on "next page"?
Thank you!
UPDATES:
if i change the code into this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
it gives me an empty list when i click on "next page".
it might be tempted to add IsPostBack, but this not work.
Add the NewPageIndex code in the PageIndexChanging event:
managerList.PageIndex = e.NewPageIndex;
bindgrid();
Below might help you
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
You need to put your code under !IsPostBack() in the page_load event. like...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
Reason: Whenever you hit the Next button, your page load event is called before the PageIndexChanging Event handler of Gridview.
Page_Load fires every time the page is loaded, including postbacks, so your select statement is getting reset. Try setting a viewstate value to keep your select statement.
Store the most recent SQL Query in a global static string and then use the following code.
static String previousSQL_Query;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlDataSource2.SelectCommand = previousSQL_Query;
}
else
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
previousSQL_Query = SqlDataSource2.SelectCommand;
managerList.DataBind();
}
Related
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
string SQL=string.Empty;
SqlDataAdapter commandToBeLog=null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SQL = " SELECT * FROM tbl_Video";
if (txtSearchVideo.Text.Trim() != string.Empty)
{
SQL += " WHERE VideoName LIKE #VideoName ";
ListView1.DataSource = null;
}
SQL += " ORDER BY VideoID DESC";
DataSet ds = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(
SQL, con);
if (txtSearchVideo.Text.Trim() != string.Empty)
{
myCommand.SelectCommand.Parameters.Add("#VideoName", SqlDbType.NVarChar, 300).Value = "%" + txtSearchVideo.Text + "%";
}
myCommand.Fill(ds);
ListView1.DataSource = ds;
ListView1.DataBind();
}
protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
this.GetData();
}
protected void btnSerch_Click(object sender, EventArgs e)
{
if (txtSearchVideo.Text.Trim() != string.Empty)
{
GetData();
GetData();
}
else
{
GetData();
}
}
Hi, how do i make the list view paging is no depedent to the textbox search. I got a problem with listview search pager, whenever I click search button with textbox value equal to A, the btnSerch_Click event fire. It show out 3 pages data with results and then I navigate to page 3. But when I type in the textbox with value B(it suppose show one page data), and I didnt click search button, but i go to click page 2. The weird thing happen, it show not relevant data or broken data.
How do i solve this problem, i don't want the page navigate bar depedent to the textbox. What I mean is I click page 2, the GetData() fucntion not fire, but just the page trigger only.
You need to to remove this line
ListView1.DataSource = null;
from the GetData method. Because if you null the ListView, the properties you set in ListView1_PagePropertiesChanging will be lost.
And you can reduce the Button click method to just one line.
protected void btnSerch_Click(object sender, EventArgs e)
{
GetData();
}
Im begginer in c # and I try to do a spin code that I found on the net.
My worry is that I would like the value of the first line of the datagrid, automatically loads itself when launching the form in a textbox.
I have this code that works fine, but it does not display any value in the textbox if I do not click on a datagrid line.
The code :
namespace SQLiteTEST
{
public partial class Form1 : Form
{
private SQLiteConnection connection;
private String SQLSelect = "SELECT * FROM User";
public Form1()
{
InitializeComponent();
connection = new SQLiteConnection("Data Source=BddTest.s3db;Version=3;");
}
private void search()
{
dataGrid1.RowEnter -= dataGrid_RowEnter;
if (connection.State != ConnectionState.Open)
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.CommandText = SQLSelect;
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command);
da.Fill(dt);
dataGrid1.DataSource = dt;
connection.Close();
dataGrid1.RowEnter += dataGrid_RowEnter;
}
private void dataGrid_RowEnter(object sender, DataGridViewCellEventArgs e)
{
int ID = int.Parse(dataGrid1.Rows[e.RowIndex].Cells[0].Value.ToString());
String Data1 = (String)dataGrid1.Rows[e.RowIndex].Cells[1].Value;
txtId.Text = ID.ToString();
txtName.Text = Data1;
}
private void Form1_Load(object sender, EventArgs e)
{
search();
}
private void dataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
MessageBox.Show("erreur");
}
private void button1_Click(object sender, EventArgs e)
{
var form_programme = new Form2();
form_programme.Show();
this.Hide();
}
private void dataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void txtName_TextChanged(object sender, EventArgs e)
{
}
private void txtId_TextChanged(object sender, EventArgs e)
{
}
private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
How could I make the first line appear in the textbox as if I was clicking on it?
Thank you in advance for your advice or sample code.
Regard.
Create a method like this:
private object GetValue(int rowIndex, int columnIndex)
{
return dataGrid1.Rows[rowIndex].Cells[columnIndex].Value;
}
I would like the value of the first line of the datagrid, automatically loads itself when launching the form in a textbox.
Use that to get any value you need. In your search method, at the end, after the data is loaded into the grid, you just need to get the values from the first row:
// first row first column.
// Use TryParse if the value is not always a number. If always a number
// then Parse is good enough
int id = int.Parse(GetValue(0, 0).ToString());
string data1 = (String) GetValue(0, 1);
txtId.Text = id.ToString();
txtName.Text = data1;
Also use .NET naming conventions so your local variables should be camel case and your method names should be Pascal notation. search should be Search.
Finaly i find how to resolve my problem !
Ill do this :
public Form1()
{
InitializeComponent();
connection = new SQLiteConnection("Data Source=BddTest.s3db;Version=3;");
search();}
Regard.
When trying to update GridView data, it successfully runs, but it gets the old data instead of the data you type in the textboxes.
This is what I have:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
GridView1.DataBind();
}
and
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
and
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
}
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
For example, the current data is:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
I type in new data:
name: John, phone: 555-555-5555, email: test2#test2.com, contactId: 22
Data that ends up in the database:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
}
Every time the page posts back you are rebinding the grid. Move the binding of the grid into a separate function. After you do the row updating, rebind the grid.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
BindGrid();
}
When you edit you must call BindGrid too.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind(); this is meaningless, you have not set a DataSource
BindGrid();
}
When you raise the RowUpdating event your basically getting the values BEFORE the GridView updates the row. This is basically so you can cancel the update operation. To get what you've type in I think you need to get the new values (the Dictionary e.NewValues() in your case).
In your case you can use it something like this (assuming name, phone and email are what they're called in your gridview):
foreach(DictionaryEntry de in e.NewValues())
{
string name = de.FirstOrDefault(x => x.Key == "name").Value;
string phone = de.FirstOrDefault(x => x.Key == "phone").Value;
string email = de.FirstOrDefault(x => x.Key == "email").Value;
}
NOTE: If you're simply using this to get the values typed in to update your database then you're better of binding the datagrid and use the value after that to ensure you definitely have the same values in the datagrid as to what you put into the database. Alternatively, use the RowUpdated event instead of the RowUpdating event.
The most prevalent reason is that we usually forgot to check the postbacks in the Page Load event.
check the post-back, then the problem will be removed.
if (! IsPostBack)
{
readData();
...
}
Prokzy I have just your example on my side and doing something like this worked fine for me. notice the DataSource portion. I have a DataSet instantiated as aDataSet btw
protected void GridView1_GridViewPageEventArgs e(object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
GridView1.DataSource = null;
GridView1.DataSource = aDataset;
GridView1.DataBind();
}
You need to call LoadContacts again and reassign GridView1.DataSource after the database is updated. Currently, the DataSource is not being updated - and is just using the collection that was retrieved prior to the row update.
i have a problem as subject said.
i have a Table courses in sql server Fields are courseID and course.
what i want is list the course in dopdown and i succeeeded but what i'm not able to do is when i select a course from dropdown list, a courseID should be selected in HiddenField/textbox/label
how to do that
here is a code i tried::
protected void Page_Load(object sender, EventArgs e)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --");
DropDownList1.SelectedIndex = 0;
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(dt.Rows[i][1].ToString());
DropDownList1.DataValueField = dt.Rows[i][0].ToString();
DropDownList1.DataTextField = dt.Rows[i][1].ToString();
}
}
in dropdownlist i'm getting values in Page Load method
i also tried dropdownlist_selectedindex change method too to select courseID
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LLabel1.Text = DropDownList1.SelectedValue.ToString();
}
what i'm doing wrong ???
Place a block of if (!IsPostBack) before you update the dropdown in your page_load
The problem is that your code will re-populate the dropdown menu after the DropDownList1_SelectedIndexChanged event will be triggred.
That will make a post request to the server and he will run the DropDownList1_SelectedIndexChanged function attached to the IndexChange event and then page_load
because the page suppose to be loaded again
and will result in a new selected value that will not be what you expect it to be.
One more thing: use string identifiers when getting a value from a Row of a DataTable the code will be much more friendly that way. (Readability is very important...)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --");
DropDownList1.SelectedIndex = 0;
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(dt.Rows[i]["CourseName"].ToString());
DropDownList1.DataValueField = dt.Rows[i]["CourseID"].ToString();
DropDownList1.DataTextField = dt.Rows[i]["CourseName"].ToString();
}
}
}
try this
above code you manually add item to dropdownlist so you have to add datavalue as well as
protected void Page_Load(object sender, EventArgs e)
{
if(!Ispostback)
{
string select = "select * from courses";
DropDownList1.Items.Add("-- Select Course --","0");
DataTable dt = con.select_command(select);
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(new listitem(dt.Rows[i][1].ToString(),dt.Rows[i][0].ToString();
));
}
DropDownList1.SelectedIndex = 0;
}
}
and your select index change event
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LLabel1.Text = DropDownList1.SelectedValue.ToString();
}
I have a combobox and a list of values in it.
If I add a value and save it, it should appear in the combobox. But it only appears after I refresh the page. It does not bind the data properly.
I have put DataBind() in
if (!Page.IsPostBack)
{
DataBind() ;
}
But the above does not help.
How do I check if everything is binding correctly or not.
Please help.
Thank you
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
if (!Page.IsPostBack)
{
}
}
protected void btn_save_click(object sender, EventArgs e)
{
SqlCommand command_update = new SqlCommand("Update", connection_save1);
command_update.CommandType = System.Data.CommandType.StoredProcedure;
command_update.Parameters.Add(new SqlParameter("#ViewId", Int32.Parse(Id.Value)));
SqlParameter Returns = new SqlParameter("#ReturnCode", SqlDbType.Char);
Returns.Size = 1;
Returns.Direction = ParameterDirection.Output;
command_insert.Parameters.Add(Returns);
bSuccess = command_insert.Parameters["#ReturnCode"].Value.ToString();
if (bSuccess == "1")
{
//Response.Write("Insert successful");
dd_group.DataBind();
dd_group.SelectedValue = command_insert.Parameters["#ReturnCode"].Value.ToString().Trim();
}
}
here is the html
<asp:DropDownList ID="dd_group" DataSourceID="sp" DataTextField="maintitle"
DataValueField="Id" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="group_SelectedIndexChanged1" Height="24px"
Width="50%">
</asp:DropDownList>
<asp:SqlDataSource ID="sp" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="GetIds" runat="server" SelectCommandType="StoredProcedure">
protected void Pre_Render(object sender, EventArgs e)
{
DataBind();
}
protected void btn_save_click(object sender, EventArgs e)
{
SqlCommand command_update = new SqlCommand("Update", connection_save1);
command_update.CommandType = System.Data.CommandType.StoredProcedure;
command_update.Parameters.Add(new SqlParameter("#ViewId", Int32.Parse(Id.Value)));
SqlParameter Returns = new SqlParameter("#ReturnCode", SqlDbType.Char);
Returns.Size = 1;
Returns.Direction = ParameterDirection.Output;
command_insert.Parameters.Add(Returns);
bSuccess = command_insert.Parameters["#ReturnCode"].Value.ToString();
if (bSuccess == "1")
{
//Response.Write("Insert successful");
dd_group.DataBind();
dd_group.SelectedValue = command_insert.Parameters["#ReturnCode"].Value.ToString().Trim();
}
}
you can use a webmethod to add elements to the combobox and when you add any item use jquery or even javascript and call this webmthod where u rebind the data
You have to call DataBind() after you update your data source: this is normally done in some control event handler which is called after Page_Load() event and therefore this invocation is only visible after your refresh (then it is called for the second time, the first time after your update).
So, just add DataBind() to your method where you perform the update, something like:
mycontrol.DataSource = newvariable;
mycontrol.DataBind();