I have a CheckBox in GridView cell. I want to update the database on CheckBox change, like when I unchecked it, 'Status' column in table update as false or vice versa.
Your question is very incomplete. But i'll give it a try, maybe it's helpful anyway.
Assuming you want to update as soon as the Checked state has changed(the user clicked the CheckBox), you have to set AutoPostBack="true" first.
Then you can handle the CheckBox.CheckedChanged event:
protected void Check_Clicked(Object sender, EventArgs e)
{
// get the checkbox reference
CheckBox chk = (CheckBox)sender;
// get the GridViewRow reference
GridViewRow row = (GridViewRow) chk.NamingContainer;
// assuming the primary key value is stored in a hiddenfield with ID="HiddenID"
HiddenField hiddenID = (HiddenField) row.FindControl("HiddenID");
string sql = "UPDATE dbo.Table SET Status=#Status WHERE idColumn=#ID";
using (var con = new SqlConnection(connectionString))
using (var updateCommand = new SqlCommand(sql, con))
{
updateCommand.Parameters.AddWithValue("#ID", int.Parse(hiddenID.Value));
// assuming the type of the column is bit(boolean)
updateCommand.Parameters.AddWithValue("#Status", chk.Checked);
con.Open();
int updated = updateCommand.ExecuteNonQuery();
}
}
Grid source
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:CheckBox ID="chkview" runat="server" AutoPostBack="true" OnCheckedChanged="chkview_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
C# code
protected void chkview_CheckedChanged(object sender, EventArgs e)
{
// code here.
}
Related
I am developing a Web Form, where I show Gridview with data. One of the column consists of CheckBox. How can I update data in particular row.
so my question is:
How to unidentified particular row and send an sql request with UPDATE when user Check or Uncheck the CheckBox?
Update:
Here is my code that i have. It doesn't update value of CheckBox.
namespace:
public partial class Call_Bills : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string check;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Submit(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView2.Rows)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
con.Open();
bool private1 = (row.FindControl("CheckBox1") as CheckBox).Checked;
if (private1 == true)
{
check = "1";
}
else
{
check = "0";
}
SqlCommand cmd = new SqlCommand("insert into DetailCosts(private) values(#private)", con);
cmd.Parameters.AddWithValue("#private", check);
cmd.ExecuteNonQuery();
}}
name of GridView is: GridView2;
name of Checkbox in the Table: private;
id of CheckBox in Gridview is:
<asp:TemplateField HeaderText="Private" SortExpression="private">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("private") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
you can manually define a method to handle a postback generated by a control inside a gridview column. To do that you just need to add the tags AutoPostBack=True and OnCheckedChanged=YourMethodName to the control.
On the code-behind, define this method as public void, and define the parameters that usually would be there (sender as object and e as EventArgs), like:
public void YourMethodName(object sender, EventArgs e)
On the method, you may need to get the GridViewRow which contains the control that has generated the event. To do that, just parse the sender parameter (which will be the checkbox) and get 2 parent levels (GridViewCell and GridViewRow), it would be something like:
GridViewRow row = ((CheckBox)sender).parent.parent;
Since you have the row, you may get any control inside it with the FindControl method. If you need an id to identify the entitiy being updated, you may store it in a hidden field inside the row.
Hope it helps!
I have a table for projects that has a bit value for whether the project is still active or not. I created a stored procedure that pulls the project name and the value for the project (0 for inactive, 1 for active). When I display it on my webpage, the bit values show up in checkboxes (which is good because I would like to be able to update those values with a button).
The problem is that I'm unable to click or unclick them.
How could I pull my data correctly so that the checkboxes for the project name is clickable to be updated?
Any help would be much appreciated.
public void loadProj()
{
SqlConnection con;
DataTable dt = new DataTable();
string CS = ConfigurationManager.ConnectionStrings["ProjDB"].ConnectionString;
using (con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetProjActive", con);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
callStoredProcedure(cmd, sa);
sa.Fill(dt);
GridView.DataSource = dt;
GridView.DataBind();
}
}
You need to set up a asp:TemplateField in your GridView columns, with a asp:CheckBox control inside this template.
Setting the CheckBox value: The Boolean database value should be bound into the CheckBox using the OnRowDataBound event.
Changing the database value: Register a OnCheckedChanged event on the template field's CheckBox control.
HTML markup:
<asp:GridView ID="gv"
runat="server"
DataSourceID="..."
OnRowDataBound="gv_DataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk_selection" runat="server" OnCheckedChanged="chk_selection__CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
....
</Columns>
</asp:GridView>
Code behind:
protected void gv_DataBound(object sender, GridViewRowEventArgs e)
{
// Get this row's CheckBox control
CheckBox chkSelector = (CheckBox)e.Row.FindControl("chk_selection");
// Cast the database boolean value and set the checkbox's Checked property
chkSelector.Checked = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "bool_field"));
}
protected void chk_selection__CheckedChanged(object sender, EventArgs e)
{
// Update your database
}
I have drop-down inside of a gridview so when the gridview is loaded and the drop-down is bound then the drop-down only show the first value of the drop-down list and it is not showing the previously selected value. When the gridview loads, i would like the drop-down to show what was previously selected for that row. Here is my code:
aspx markup for the drop-down:
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</ItemTemplate>
Here is code behind:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
//get current index selected
int current_quest = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
{
con2.Open();
using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 where ID= '" + current_quest + "' ", con2))
{
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
}
con2.Close();
}
}
I have tried to add this line of code after binding but i get this error "Object reference not set to an instance of an object"
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
thanks
I believe in your SELECT you need to use current_quest_sk instead of current_quest
Aslo try to check for null before accessing your controls:
var ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
var answerLabel = e.Row.FindControl("lblAns") as Label;
if(answerLabel !=null && ddl_Answer!=null)
{
ddl_Answer.Items.FindByValue(answerLabel.Text).Selected = true;
}
#afzalulh has a valid point remove quotes if current_quest_sk(ID) is an Integer in your table.
You should avoid SQL injection but that's a different topic.
Place a breakpoint in your code, and setup through it with your debugger.
Either you have a typo in one of your string names or you are looking at the wrong control.
Stepping through your code will help you see exactly what line of your code is causing the problem.
You could also put a try/catch block around the whole thing to help you isolate the problem. Once you find the problem, remove the try/catch block.
I am wondering how I can get the value from an asp.net textbox that is dynamically created inside an asp:datalist.
I would like to then insert these values back into the database.
Let say we have the following output on the web page from the datalist. (Each Question is a asp:textbox)
Question 1
Answer 1
Answer 2
Update Button
Question 2
Answer 1
Answer 2
Update Button
Question 3
Answer 1
Answer 2
Update Button
For example: I would like to get the value from Question 2 textbox and then parse the value to my database insert method.
How can this be done as the text boxes are generated dynamically in the data list?
I have written the following:
<asp:DataList runat="server" id="dgQuestionnaire" DataKeyField="QuestionID" CssClass="confirm">
<ItemTemplate>
<h3>Question <asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label></h3>
<asp:TextBox runat="server" ID="QuestionName" Text='<%# Eval("QuestionText") %>' CssClass="form"></asp:TextBox>
<asp:DataList ID="nestedDataList" runat="server">
<ItemTemplate>
<asp:TextBox ID="AnswerBox" runat="server" CssClass="form" Text='<%# Eval("AnswerTitle") %>' Width="300px"></asp:TextBox>
</ItemTemplate>
</asp:DataList>
<asp:Button runat="server" ID="updateName" CssClass="button_update" style="border: 0px;" onClick="UpdateQuestionName_Click" />
</ItemTemplate>
</asp:DataList>
And here the code behind (sorry about the length)
protected void UpdateQuestionName_Click(object sender, EventArgs e)
{
int QuestionnaireId = (int)Session["qID"];
GetData = new OsqarSQL();
// Update question name
GetData.InsertQuestions(QuestionName.Text, QuestionnaireId);
} // End NewQNRButton_Click
public void BindParentDataList(int QuestionnaireID)
{
_productConn = new SqlConnection();
_productConnectionString += "data source=mssql.myurl.com; Initial Catalog=database_2;User ID=userid;Password=aba123";
_productConn.ConnectionString = _productConnectionString;
SqlCommand myCommand = new SqlCommand("GetQuestion", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("#QUEST_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = QuestionnaireID;
// check the connection state and open it accordingly.
_productConn.Open();
// Sql datareader object to read the stream of rows from SQL Server Database
SqlDataReader myDataReader = myCommand.ExecuteReader();
// Pass the Sql DataReader object to the DataSource property
// of DataList control to render the list of items.
dgQuestionnaire.DataSource = myDataReader;
dgQuestionnaire.DataBind();
// close the Sql DataReader object
myDataReader.Close();
// check the connection state and close it accordingly.
if (_productConn.State == ConnectionState.Open)
_productConn.Close();
// foreach loop over each item of DataList control
foreach (DataListItem Item in dgQuestionnaire.Items)
{
BindNestedDataList(Item.ItemIndex);
}
}
public void BindNestedDataList(int ItemIndex)
{
int QuestionID = Convert.ToInt32(dgQuestionnaire.DataKeys[ItemIndex]);
SqlCommand myCommand = new SqlCommand("GetAnswer", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#QUESTION_ID", SqlDbType.Int).Value = QuestionID;
// check the connection state and open it accordingly.
if (_productConn.State == ConnectionState.Closed)
_productConn.Open();
// Sql datareader object to read the stream of rows from SQL Server Database
SqlDataReader myDataReader = myCommand.ExecuteReader();
// findControl function to get the nested datalist control
DataList nestedDataList = (DataList)dgQuestionnaire.Items[ItemIndex].FindControl("nestedDataList");
nestedDataList.DataSource = myDataReader;
nestedDataList.DataBind();
// close the Sql DataReader object
myDataReader.Close();
// check the connection state and close it accordingly.
if (_productConn.State == ConnectionState.Open)
_productConn.Close();
}
How can I get the value of a textbox when its corresponding button "updateName" is pressed?
Thanks
You can try doing something like this (code updated):
protected void UpdateQuestionName_Click(object sender, EventArgs e)
{
int QuestionnaireId = (int)Session["qID"];
GetData = new OsqarSQL();
//get the button that caused the event
Button btn = (sender as Button);
if (btn != null)
{
//here's you question text box if you need it
TextBox questionTextBox = (btn.Parent.FindControl("QuestionName") as TextBox);
// Update question name
GetData.InsertQuestions(questionTextBox.Text, QuestionnaireId);
//and in case you want more of the associated controls
//here's your data list with text boxes
DataList answersDataList = (btn.Parent.FindControl("nestedDataList") as DataList);
//and if answersDataList != null, you can use answersDataList.Controls to access the child controls, where answer text boxes are
}
} // End NewQNRButton_Click
This should work as you want.
I have an asp.net GridView:
<asp:TemplateField HeaderText="View Faktor" ShowHeader="False" Visible="True">
<ItemTemplate>
<asp:ImageButton ID="imgBtn1" CssClass="SelectRow" runat="server" CausesValidation="false"
CommandArgument='<%#(eval("mprID")) %>' CommandName="ViewFactors" ImageUrl="~/tadarokat/Images/factor.png"
Text="" />
</ItemTemplate>
</asp:TemplateField>
How Can I get rowIndex on row command event?
I want to highlight (select) target row when RowCommand fires.
this is answer for your question.
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
int RowIndex = gvr.RowIndex;
ImageButton \ Button etc.
CommandArgument='<%# Container.DataItemIndex%>'
code-behind
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = e.CommandArgument;
}
Or, you can use a control class instead of their types:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int RowIndex = row.RowIndex;
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
I was able to use #rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.
Here is my solution:
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["Products"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["Products"] = dt;
}
}
catch (Exception ex)
{
throw;
}
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
gvProductsList.DataSource = ViewState["Products"];
gvProductsList.DataBind();
}
catch (Exception ex)
{
}
}