How to show unique key exception before saving into database? - c#

I've created a gridview in which user can enter items and their quantities. The number of items are unknown so the requirement was that to able to add as much items the users want to. So I've given a provision to add item row for another entry. All these data entered gets into a temporary table and one all done by click on a button all these datas will save onto database.
Is there any way to hide the items which has been already selected on the previous row or show an error that the item has been already enter while selecting the dropdown value, before clicking on the button.
My gridview looks something like this:
gridview code:
<asp:GridView ID="gvItemList" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" CssClass="newStyle9" ForeColor="Black" OnRowDataBound="gvItemList_RowDataBound" OnRowDeleting="gvItemList_RowDeleting" ShowFooter="True" style="text-align: center" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField HeaderText="Sl No" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text="<%# Container.DataItemIndex+1 %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" AutoPostBack="True" OnSelectedIndexChanged="ddlItem_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit">
<ItemTemplate>
<asp:Label ID="txtUnit" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server" Height="27px" Width="73px"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" OnClick="ButtonAdd_Click" Text="Add New Item" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code behind:
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("lblId");
tempDataTable.Columns.Add("ddlItem");
tempDataTable.Columns.Add("txtUnit");
tempDataTable.Columns.Add("txtQty");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempDataTable;
gvItemList.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's values
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[i - 1]["ddlItem"] = Item.SelectedValue;
tempTable.Rows[i - 1]["txtUnit"] = Unit.Text;
tempTable.Rows[i - 1]["txtQty"] = Qty.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempTable;
gvItemList.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
Item.SelectedValue = tempTable.Rows[i]["ddlItem"].ToString();
Unit.Text = tempTable.Rows[i]["txtUnit"].ToString();
Qty.Text = tempTable.Rows[i]["txtQty"].ToString();
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void gvItemList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
deleteRow(index);
SetPreviousData();
if (gvItemList.Rows.Count == 0)
{
SetInitialRowToGrid();
}
}
private int deleteRow(int index)
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
}
// Add data to datatable and viewstate
tempTable.Rows.RemoveAt(index);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempTable;
gvItemList.DataBind();
}
}
//Set Previous Data on Postbacks
return index;
}
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
Jilu1TableAdapters.tbl_ItemTableAdapter item;
item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItems();
ddlItem.DataSource = dt;
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
}
}
private void InsertRecords(StringCollection sc)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
string user = Page.User.Identity.Name;
try
{
foreach (string item in sc)
{
if (item.Contains(",,,"))
{
//To prevent null reference error
}
else
{
splitItems = item.Split(",".ToCharArray());
ds.InsertJrBOM(ddlState.SelectedValue, ddlDistrict.SelectedValue, ddlCluster.SelectedValue, ddlSiteID.SelectedValue, txtSiteName.Text, ddlSiteType.SelectedValue, txtNoBTS.Text, txtNoLinks.Text, txtLoadBand.Text, ddlEBAvailability.SelectedValue, txtEBPhase.Text, txtDGCapacity.Text, txtDGPhase.Text, splitItems[0], splitItems[1], splitItems[2], user, DateTime.Now, "Nil", 1, txtDispatch.Text);
}
}
lblSuccess.Visible = true;
lblSuccess.Text = "Records Successfully Saved!";
Timer1.Enabled = true;
}
catch (System.Data.SqlClient.SqlException)
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Duplicate Items has been entered, please correct it before proceeding or an entry for " + ddlSiteID.Text + " has already made, please go to edit page to make necessary changes!";
Timer1.Enabled = true;
return;
}
catch (Exception ex)
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Error: " + ex.Message;
Timer1.Enabled = true;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["TempTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
DropDownList ddlItem = (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
Label txtUnit = (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
TextBox txtQty = (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(ddlItem.SelectedValue + "," + txtUnit.Text + "," + txtQty.Text);
if (sc.Contains(",,,"))
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Fields should not be left empty!";
Timer1.Enabled = true;
return;
}
else
{
string Quantity = txtQty.Text;
float num;
if (float.TryParse(Quantity, out num))
{
rowIndex++;
}
else
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Quantity field must be a number!";
Timer1.Enabled = true;
return;
}
}
}
//Call the method for executing inserts
InsertRecords(sc);
if (lblSuccess.Text == "Records Successfully Saved!")
{
this.SetInitialRowToGrid();
string user = Page.User.Identity.Name;
StatusTableAdapters.tbl_NotificationsTableAdapter ds2;
ds2 = new StatusTableAdapters.tbl_NotificationsTableAdapter();
ds2.InsertNotification(ddlSiteID.SelectedValue, "BOM Notification", DateTime.Now, user, "Role6");
}
}
}
}
Any help will be greatly appreciated.

protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)
{
var main = (sender as DropDownList);
foreach (GridViewRow row in gvItemList.Rows)
{
var ddl = (row.FindControl("ddlItem") as DropDownList);
if (main.ClientID != ddl.ClientID && ddl.SelectedValue == main.SelectedValue)
{
row.BackColor = System.Drawing.Color.Red;
string script = "alert('already selected!');";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}

Related

Binding GridView Columns to CheckBoxList Dynamically in C#

I want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.

C# - Transfer value from one page to a dynamic gridview's textbox

Here is my aspx page, describing a dynamic gridview:
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True"
AutoGenerateColumns="False"
OnRowCreated="Gridview1_RowCreated" style="margin-left: 13px; margin-right: 6px; margin-top: 12px;" Width="1035px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="#" />
<asp:TemplateField HeaderText="Disease">
<ItemTemplate>
<asp:Button ID="Icd" runat="server" Text="ICD 10" Height="23px" Width="69px" OnClick="Icd_Click" />
<asp:TextBox ID="TextBox1" runat="server" Height="23px" Width="301px" MaxLength="100"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Height="23px" Width="95px" MaxLength="4"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stuation">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AppendDataBoundItems="true" Height="23px">
<asp:ListItem Value="-1">--Επιλέξτε--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Therapy">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Height="23px" Width="223px" MaxLength="100"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="+Add new row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
onclick="LinkButton1_Click">Delete row</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#006466" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
And here is the aspx.cs code:
private ArrayList GetDummyData()
{
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Πάσχει", "1"));
arr.Add(new ListItem("Έπασχε", "2"));
return arr;
}
private void FillDropDownList(DropDownList ddl)
{
ArrayList arr = GetDummyData();
foreach (ListItem item in arr)
{
ddl.Items.Add(item);
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Bind the Gridview
Gridview1.DataSource = dt;
Gridview1.DataBind();
//After binding the gridview, we can then extract and fill the DropDownList with Data
DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
FillDropDownList(ddl1);
}
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
dtCurrentTable.Rows[i]["Column4"] = box3.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox3");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
if (i < dt.Rows.Count - 1)
{
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
box3.Text = dt.Rows[i]["Column4"].ToString();
}
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null)
{
if (dt.Rows.Count > 1)
{
if (e.Row.RowIndex == dt.Rows.Count - 1)
{
lb.Visible = false;
}
}
else
{
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
//Remove the Selected Row data and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
if (Session["pa_id"] != null)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO P_deasease (Date,P_Id,Nosos,Situ,Year_d,Therapy) VALUES";
int id = Convert.ToInt32(Session["pa_id"]);
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}(#Date, #p_id ,N'{1}',N'{2}',N'{3}',N'{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
{
cmd.Parameters.AddWithValue("#p_id", id);
cmd.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Success!";
}
else
{
lblid1.Visible = true;
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
//add them to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, ddl1.SelectedItem.Text, box2.Text, box3.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
As you can see in the 1st column there is a button along with a textbox.
When you click the button, a popup window appears in which there is something like "search-in-the-database" mechanism.
So, when a value is selected in the popup window's gridview, I want to transfer it to the corresponding text box.
How do I transfer the value into the corresponding textbox? As a beginner, I am dealing a great difficulty into that part. Any help will be appreciated

GridView with CheckBox: How To Get Selected Rows in ASP.Net

How to get gridview row values when checkbox is checked. I am using this code in button's click event, but it's not working .
Html Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333"
PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
I can not see how you bound data and where is your button placement. So this is work sample.
<asp:Button Text="text" runat="server" OnClick="Unnamed_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId" Width="100%"
ForeColor="#333333" PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = new RowModel[]
{
new RowModel { ReportId = "1" },
new RowModel { ReportId = "2" },
new RowModel { ReportId = "3" }
};
GridView1.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
public class RowModel
{
public string ReportId { get; set; }
}
In My sample code I have consider manually data while binding gridview because as you don't specify how you have bind your gridview through database or not, but it should work in both approaches.
My HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true" onclick="btnProcess_Click" />
<br />
<asp:Label ID="lblmsg" runat="server" />
</div>
</form>
</body>
</html>
Code Behind: This is just for binding GridView with proper data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 1; //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 2; //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 3; //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
Code of Button_Click event
protected void btnProcess_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
string edu = string.Empty;
string location = string.Empty;
foreach (GridViewRow gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
//To Fetch the row index
//str += gvDetails.SelectedIndex.ToString();
//To Fetch the value of Selected Row.
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text + ',';
edu += gvrow.Cells[3].Text + ',';
location += gvrow.Cells[4].Text + ',';
}
}
str = str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b><br>" + " Education: <b>" + edu + "</b><br>" + " Location: <b>" + location + "</b><br>";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count= 0;
foreach (GridViewRow gvindex in GridView1.Rows)
{
CheckBox chck = gvrow.FindControl("CheckBoxG1") as CheckBox;
if (chck.Checked)
{
GridView1.EditIndex = count;
DataBind(); //Your Databind Function
}
count++;
}

How to Keep row values in gridview after adding new row?

I have a gridview with textboxes for item no, desc qty, cost, extncost. When itemno entered in the textbox desc and cost of the item will comes automatically by on textbox event change.
Here when i add a new row in the grid view, values of last entered value got disappears.
when i am checking using break point i can able to see the last entered values in data table.
Since, while adding new row has blank text boxes, now system considers blank text box for on text change event. So, last entered values also not displaying. Text box changes in one row also affects in other rows.
Here is the ASPX.page code:
<asp:UpdatePanel ID="gin_pnlupdt" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="grv_gindet" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting"
OnRowDataBound="grv_gindtrowcmd" OnRowCommand="grv_gindetrowcmd">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Item Number">
<ItemTemplate>
<asp:TextBox ID="txt_itemno" runat="server" OnTextChanged="txt_itemno_changed" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:Label ID="txt_itemdesc" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_qty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Cost">
<ItemTemplate>
<asp:Label ID="txt_ucost" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extended Cost">
<ItemTemplate>
<asp:Label ID="txt_extncost" runat="server"></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="BtnAddRow" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grv_gindet" />
</Triggers>
</asp:UpdatePanel>
Here is the CS code for add new row:
protected void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxItem =
(TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc =
(Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxItem.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxDesc.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxQty.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = TextBoxucost.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = TextBoxextncost.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grv_gindet.DataSource = dtCurrentTable;
grv_gindet.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
Code for retrive Previous data:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox TextBoxItem = (TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc = (Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
TextBoxItem.Text = dt.Rows[i]["Col1"].ToString();
TextBoxDesc.Text = dt.Rows[i]["Col2"].ToString();
TextBoxQty.Text = dt.Rows[i]["Col3"].ToString();
TextBoxucost.Text = dt.Rows[i]["Col4"].ToString();
TextBoxextncost.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
Textbox change event:
protected void txt_itemno_changed(object sender, EventArgs e)
{
//TextBox thisTextBox = (TextBox)sender;
//GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
//int row = thisGridViewRow.RowIndex;
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
grv_gindet.Rows[row].Cells[2].Text = dr["ITEMDESC"].ToString();
grv_gindet.Rows[row].Cells[4].Text = dr["UNITCOST"].ToString();
}
}
thisTextBox.Enabled = false;
}
Postback control code for gridview child element:
protected void grv_gindtrowcmd(object sender, GridViewRowEventArgs e)
{
try
{
TextBox txtitm = e.Row.FindControl("txt_itemno") as TextBox;
LinkButton lnkbtn = e.Row.FindControl("ShowDeleteButton") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtitm);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lnkbtn);
}
catch
{
}
}
protected void grv_gindetrowcmd(object sender, GridViewCommandEventArgs e)
{
try
{
Button btnad = grv_gindet.FooterRow.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btnad);
}
catch
{
}
}
Kinldy provide a solution ASAP, do the needful.
I hope this will help you, change this in Textchange event
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent.Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
if (!string.IsNullOrWhiteSpace(thisTextBox.Text))
{
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
((Label)(grv_gindet.Rows[row].FindControl("txt_itemdesc"))).Text = dr["ITEMDESC"].ToString();
((TextBox)(grv_gindet.Rows[row].FindControl("txt_ucost"))).Text = dr["UNITCOST"].ToString();
}
con.Close();
}
thisTextBox.Enabled = false;
}

delete row in gridview

I am currently trying to delete record in grid view which stored in memory
A bit background, The grid currently populate based on selected file on Asp.net fileUpload control.
So, when the user choose the files from file upload and click Add Files, the the files add to the grid. The files is stored on physical location or database. It currently stored in memory.
<asp:FileUpload ID="file_upload" runat="server" AllowMultiple="true" maxLength="10" accept="text/plain" Enabled="false"/>
<asp:GridView ID="GridFiles" runat="server" AutoGenerateDeleteButton="True" Height="122px" ShowFooter="True" Style="left: 173px;
top: 84px" Width="532px" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" OnRowDeleting="GridFiles_RowDeleting">
<AlternatingRowStyle BorderColor="#FFC0C0" />
<FooterStyle BackColor="White" ForeColor="#333333" />
<RowStyle BackColor="White" BorderStyle="Dotted" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<emptydatatemplate>
<center> No Files have been selected for upload.</center>
</emptydatatemplate>
</asp:GridView>
<asp:Button ID="btnAdd" runat="server" Text="Add Files" onclick="btnAdd_Click" CssClass="submit"/>
.aspx.cs
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt;
DataRow dr = null;
FileInfo fileObj = new FileInfo(file_upload.PostedFile.FileName);
//string FileName = file_upload.PostedFile.FileName;
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
string FileName = userPostedFile.FileName;
try
{
if (GridFiles.Rows.Count > 0)
{
int count = GridFiles.Rows.Count;
dt = new DataTable();
DataColumn dcFileName = new DataColumn("File Name", typeof(string));
dt.Columns.Add(dcFileName);
for (int j = 0; j < count; j++)
{
if (GridFiles.Rows[j].Cells[1].Text == FileName)
{
lblMessage.Text = "File already in the list";
break;
}
}
for (int k = 0; k < count; k++)
{
dr = dt.NewRow();
dr["File Name"] = GridFiles.Rows[k].Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["File Name"] = FileName;
dt.Rows.Add(dr);
GridFiles.DataSource = dt;
GridFiles.DataBind();
}
else
{
dt = new DataTable();
DataColumn dcFileName = new DataColumn("File Name", typeof(string));
dt.Columns.Add(dcFileName);
dr = dt.NewRow();
dr["File Name"] = FileName;
dt.Rows.Add(dr);
GridFiles.DataSource = dt;
GridFiles.DataBind();
}
}
catch (Exception ex)
{
lblMessage.Text = "Error: <br>" + ex.Message;
}
protected void GridFiles_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//TODO delete
}
You need to add a DataKeyNames value to the gridview and a corresponding column in the datatable holding your info and populate it with some id to identify each row. Then try this code at the click event of a delete button placed at each row
GridViewRow gvRow = (GridViewRow)((Button)sender).Parent.Parent;
int ID = Convert.ToInt32(grdView.DataKeys[gvRow.RowIndex]["ID"]);
DataTable grdContent = (DataTable)ViewState["grdContent"];
foreach (DataRow dr in grdContent.Rows)
{
if (dr["ID"].ToString() == ID.ToString())
{
grdContent.Rows.Remove(dr);
grdContent.AcceptChanges();
break;
}
}
grdView.DataSource = grdContent;
grdView.DataBind();

Categories