Gridview rebind data with new parameters - c#

OK, so I need to change the values stored in my gridview based on input from user.
I used to filter it 100% with javascript, but it turns out that it needs to be paged, so that wont work. Instead, I have to call on the datasource again, but with parameters from the textbox.
I've figured out that I must call a function in code behind and from there call DataBind(), but I dont even know where to start. Please help
I know that I ought to post some code to show that I've made an effort, but I really dont have anything to show. i guess it would be something along these lines?:
protected void ReBind(string sParameter)
{
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}
But obviously I'm fumbling in the dark here.

Take a update button
Write method for update function
public int update_method(string ParameterName)
{
module c = new module();
c.DB_Connection();
int i;
string QRY = "UPDATE TableName SET Parameter_Name='" + ParameterName + "' WHERE Parameter_Name='" + ParameterName + "'";
SqlCommand CMD = new SqlCommand(QRY, c.con);
i = CMD.ExecuteNonQuery();
return i;
}
on button click
protected void ButtonUpdate_Click1(object sender, EventArgs e)
{
update_method(ParameterNametxt.Text);
}
update_method(farm, common_obj);

Turns out that this worked out fine:
protected void ReBind(String sParameter)
{
SqlDataSource.SelectParameters.Remove(SqlDataSource.SelectParameters["parameterName"]);
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}

Related

Why delete command is not executing from c#?

Please check the following code:
protected void Button2_Click(object sender, EventArgs e)
{
string y = foredidel.Text;
try
{
using (var sc = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM fixap WHERE Id = #word";
cmd.Parameters.AddWithValue("#word", y);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.Write("Error");
}
}
When the button is clicked, the specified row should be deleted, but it's not doing anything!
Is there something wrong in my code?
My code was working along with some javascript, so it was like....
onclick give id's value to innerHtml of <asp:Label>.
Then take that value to the variable y in C#(you can check my question for
that variable).
Now as it was runat='server', so I used it to concatenate with my
SqlCommand("#word", y).
I don't know if it was a problem of <asp:Label>, but when I changed it to <asp:TextBox> it worked successfully!
So, answer is just to change <asp:Label> to <asp:TextBox> and according to 1st point change innerHTML to value, and it worked!

Assign a value to drop down list on page_load

I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.
After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown();
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
}
protected void FillDropDown()
{
using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);
DataTable dt = new DataTable("Test");
adp.Fill(dt);
ddlVehicleReg.DataValueField = "Id";
ddlVehicleReg.DataTextField = "Value";
ddlVehicleReg.DataSource = dt;
ddlVehicleReg.DataBind();
}
}

how to write sql query from one page to another

I am currently working on my first website. The problem I have encountered is the following: I have created a paged titled "CustomerList" that obviously list customers from an sql server DB. I have made the records clickable without using the select button that is included in the GridView. When I click a record, it takes me to my desired page. However, I can't seem to find a way to write an sql query from that click event to my desired page. The following is my code for the click event:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
if (row.RowIndex == 0)
{
Response.Redirect("UsageHistoryPage.aspx? EntityID="
+ row.Cells[0].Text);
}
}
As you can see, when I click an index, I go to the "UsageHistoryPage". I've also added row.cells.[0] to take that data and write it to the UsageHistoryPage, which in my case, would be the customers name at the top of the page. Can someone please help me with this? Does anyone have a good tutorial link? thanks.
You can try with this code - Add this code on your UsageHistoryPage
var input = Response.QueryString["EntityId"];
var connectionString = "...";
var queryString = "SELECT Name FROM TABLE WHERE COLUMN=#EntityId";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
using(var command = new SqlCommand(queryString, connection))
{
Command.Parameters.AddWithValue("#EntityId",input)
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Response.Write(String.Format("For Rick Your Name is here{0}", reader[0]));
}
}
}
#Rick you may want to look at how to check if a row is selected for example you don't need the for loop but in my case example need to check if RowIndex is = 1 or > 0 not ==0
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
What you need to do is something like this to make sure that a Row has been selected
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewRow row = GridView1.SelectedRow;
if (this.row.SelectedRows.Count == 1)
{
Response.Redirect("UsageHistoryPage.aspx?EntityID=" + row.SelectedRows[0].Cells[0].ToString());
}
}
If you want to have the Customer's name show up, on the Page Load of the UsageHistorPage.aspx add this code
String strCustName = Request.QueryString["EntityID1"];
this.Page.Title = strCustName;
try something like that.. please let someone here know if any of the ideas are working for you.

How to avoid instantiation of variable after button click?

I am running a Sql query whose where clause changes everytime when button click occurs.
Now the where clause consists of an index to the list. When the button click happens ,page load occurs which causes the index value intialisation.
int i=0;
protected void Button1_Click(object sender, EventArgs e)
{
string str = lst1.ElementAt<string>(i++);
qr = "Select BdId,First_Name,Last_Name,Age,Gender,Relationship_status,Birthday from [User] where BdId='" + str + "'";
da2 = new SqlDataAdapter(qr, con);
da2.Fill(ds2);
Label1.Text = Label1.Text + " " + i.ToString();
}
How can I avoid this happening? I want index value to be global so that it doesn't instantiate again every time button click occurs.
Thanks
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
private int TheIndex
{
set { ViewState["TheIndex"] = value; }
get
{
if (ViewState["TheIndex"] == null)
return 0;
return (int)ViewState["TheIndex"];
}
}
And use TheIndex instead of i.
EDIT
Plus, as CodeInChaos notes, use a more descriptive name. That will help in understanding the code if someone else (or you yourself in a few months) needs to maintain this code.
You can store the variable in Session object provided by ASP.Net. You can check this tutorial also.
if(Session["CurrentIndex"] != null) i = (int) Session["CurrentIndex"];
else Session["CurrentIndex"] = i;
Hope this works for you.

Problems submitting dynamic checkbox values

I'm working on creating a dynamic list of checklists and came to the below implementation. I have been trying for a week now to get the fnameID text values on the submit button click to send the values into the database. I do not want to use the postback oncheckedchanged.on each check because the checklist is over 1000 rows long and each postback/reload wastes too many resources. I just want to be able to use some method to be able to grab the checked values so I can insert them into the database on the submit button "Click Me!" click.
I googled and found the FindControl method but i still am not able to grab the fnameID values. I either get a undefined or it errors out on me. Any help would be greatly appreciated! Thanks!
aspx:
<div id="aGAccountabilityCheckListBox">
"Panel1" runat="server">
<asp:LinkButton ID="LinkButton1" Width="66px" runat="server" onclick="LinkButton1_Click">
Click Me!
</asp:LinkButton>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(" <span id='fnameID" + i + "' >test" + i + "</span>");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnDatabase"].ToString());
SqlCommand cmd = new SqlCommand("usp_CreateUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Thanks!
State is restored to controls before the load event runs. If your controls don't already exist by then, they'll lose their state and you won't know they were checked. Create your checkboxes in the Init or PreInit event instead.
move the checkbox creation to the CreateChildControls page method
to retrieve checkbox state in the LinkButton1_Click handler you can use the following code
for (int i = 0; i < 50; i++)
{
string cbxId = string.Format("dynamicCheckListBox{0}", i);
CheckBox _checkbox = Panel1.FindControl(cbxId) as CheckBox;
if (_checkbox == null )
continue;
if ( _checkbox.Checked )
//do something
}
Your fnameID's are spans created as a literal control. There is no post back value you are going to get if you set it up that way. It's just arbitrary html or text from the asp.net perspective.
Why are you not using the Text property for CheckBox?

Categories