ASP.Net - Save previous Rows - c#

I have a method which save previous data in DataTable rows. I want to click "Create" previous rows data be maintained.
private void SetOldData()
{
int rowIndex = 0;
if (ViewState["Curtbl"] != null)
{
DataTable dt = (DataTable)ViewState["Curtbl"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox txt1 = (TextBox)myGrid.Rows[rowIndex].Cells[0].FindControl("txt1");
DateTimeControl dt1 = (DateTimeControl)myGrid.Rows[rowIndex].Cells[1].FindControl("dt1");
DateTimeControl dt2 = (DateTimeControl)myGrid.Rows[rowIndex].Cells[2].FindControl("dt2");
TextBox txt2 = (TextBox)myGrid.Rows[rowIndex].Cells[3].FindControl("txt2");
TextBox txt3 = (TextBox)myGrid.Rows[rowIndex].Cells[4].FindControl("txt3");
txt1.Text = dt.Rows[i]["txt1"].ToString();
dt1.SelectedDate = dt.Rows[i]["dt1"];
dt2.SelectedDate = dt.Rows[i]["dt2"];
txt2.Text = dt.Rows[i]["txt2"].ToString();
txt3.Text = dt.Rows[i]["txt3"].ToString();
rowIndex++;
}
}
}
}
My problem is conversion between this dates :
dt1.SelectedDate = dt.Rows[i]["dt1"];
dt2.SelectedDate = dt.Rows[i]["dt2"];

Well, since SelectedDate most likely needs a Datetime and the the dt.Rows most likely returns a string, you have to parse it to a datetime:
DataTime dateValue;
if (Datetime.TryParse(dt.Rows[i]["dt1"].ToString(), out dateValue))
{
dt1.SelectedDate = dateValue;
}
(You provide very little details about error message etc...)

Related

I need helping adding two different rows(with same columns) to the same datatable

Working on a windows form application that reads in data from csv files and adds the data to a Datagridview. I ran into an issue with all of the rows being added to the datable and being displayed on the datagridview. The datagridview displays the datarows from the first two if conditions and OneRow if condition only. It will not add the rows from the twoRow if condition if the datable and datagridview rows are populated with the OneRow if condition rows. But i want the rows from both OneRow and TwoRow to be displyed. Also the rows from TwoRow do populate the datatable and datagridview when I comment(/**/) out the OneRow if condition. But I need both to populate the table. Thanks in advance!
Construct.MainDataTable.Columns.Add("Date", typeof(DateTime));
Construct.MainDataTable.Columns.Add("Time");
Construct.MainDataTable.Columns.Add("Serial");
Construct.MainDataTable.Columns.Add("Type");
Construct.MainDataTable.Columns.Add("level");
Construct.MainDataTable.Columns.Add("price");
Construct.MainDataTable.Columns.Add(" Limit");
Construct.MainDataTable.Columns.Add("last Limit");
Construct.MainDataTable.Columns.Add("Data");
..........................
...............................................
DataRow oneRow = Construct.MainDataTable.NewRow();
DataRow twoRow = Construct.MainDataTable.NewRow();
dataGridView2.AllowUserToAddRows = false;
if (line.Split(',')[2].Equals("Time"))
{
time = line.Split(',')[3];
date = line.Split(',')[1];
}
if (line.Split(',')[2].Equals("Level"))
{
level = line.Split(',')[3];
}
//OneROw(IF condition)
if ((Convert.ToDecimal(line.Split(',')[8])) < (Convert.ToDecimal (line.Split(',')[12])))
{
type = line.Split(',')[1];
serial = line.Split(',')[7];
price = line.Split(',')[3];
Limit = line.Split(',')[8];
lastLimit = line.Split(',')[10];
Data = line.Split(',')[12];
oneRow["Date"] = date;
oneRow["Time"] = time;
oneRow["Serial"] = serial;
oneRow["Type"] = type;
oneRow["level"] = level;
oneRow["price"] = price;
oneRow[" Limit"] = Limit;
oneRow["last Limit"] = lastlimit;
oneRow["Data"] = Data;
Construct.MainDataTable.Rows.Add(oneRow);
}
//TwoROw(IF condition)
if ((line.Contains('"')) && ((line.Contains("NG"))))
{
price = line.Split(',')[3];
type = line.Split(',')[1];
serial = line.Split(',')[7];
Limit = line.Split('"')[7];
var valLimit = Limit.Split(',').Select(a => Convert.ToInt32(a, 16));
var limitJoin = String.Join(",", valLimit);
lastlimit = line.Split('"')[1];
var vallastLimit = lastlimit.Split(',').Select(d => Convert.ToInt32(d, 16));
var lastJoin = String.Join(",", vallastLimit);
Data = line.Split('"')[5];
var valDatas = Data.Split(',').Select(s => Convert.ToInt32(s, 16));
var dataJoin = String.Join(",", valDatas);
twoRow["Date"] = date;
twoRow["Time"] = time;
twoRow["Serial"] = serial;
twoRow["Type"] = type;
twoRow["level"] = level;
twoRow["price"] = price;
twoRow["Limit"] = limitJoin;
twoRow["last Limit"] = lastJoin;
twoRow["Data"] = dataJoin;
Construct.MainDataTable.Rows.Add(twoRow);
}
dataGridView2.DataSource = Construct.MainDataTable;
Can't add a comment because I don't have enough karma so I ask my questions here: So, if I understood your problem you can't add data from one .csv file if it have more then one row? Why are you using 2 different if conditions for row in .csv file?
If you have empty data in row never mind you can still place them to your DataTable column, so you can use loop to add data from .csv to your DataTable. Try some thing like this:
public static DataTable CsvToDataTable(string csv)
{
DataTable dt = new DataTable();
string[] lines = csv.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
Regex onlyDeimiterComma = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
for (int i = 0; i < lines.Length; i++)
{
DataRow row = dt.NewRow();
string[] cells = onlyDeimiterComma.Split(lines[i]);
for (int j = 0; j < cells.Length; j++)
{
if (i == 0)
{
if (j == 0)
{
dt.Columns.Add(cells[j], typeof(DateTime));
}
else
{
dt.Columns.Add(cells[j]);
}
}
else
{
row[j] = cells[j];
}
}
dt.Rows.Add(row);
}
return dt;
}
Just call this method anywhere in your code and give it string read from your .csv file.
You can try to compile this code here and see how it works on .csv data with different data (empty columns, quoted text, quoted commas)
UPD: If you need to fill DataTable from two different .csv files you can still use code above. Just call it twice for both files and then Merge two DataTable, like this:
DataTable dt = CsvToDataTable(csvFileOne);
DataTable dtTwo = CsvToDataTable(csvFileTwo);
dt.Merge(dtTwo);

How to get cell value from dataTable Asp.Net

I'm creating dynamically data table bound to Grid View. Every row is populated with button. When I determine which button is clicked on the row, I want to get the current value of cell in that row modify her.
Markup:
<asp:GridView ID="GridView2" runat="server"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CommandName="odzemi"
CssClass="button2"
Font-Bold="True"
Text="-"
Width="100px"
OnClick="btnTest_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Creating the row:
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
HttpCookie cookie = Request.Cookies["Democookie"];
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
//this is where i need to make changes
drCurrentRow["Kolicina"] = Label5.text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
//determine which button is clicked in data Table
//and here
protected void btnTest_Click(object sender, EventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
count--;
decimal noofcount = count;
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
If the only problem is that you don't know how to read the old value as noted here:
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
then this works:
object oldValue = dtCurrentTable.Rows[clickedIndex]["Kolicina"];
// cast/convert it to whatever it is
or (what i prefer):
string old = dtCurrentTable.Rows[clickedIndex].Field<string>("Kolicina");
int oldValue = int.Parse(old); // in case that you don't know
int newValue = oldValue + count; // just an example
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
I'm using the Field/SetField extension methods for DataRow because it is strongly typed and even supports nullable types.
By the way, why do you store ints as strings?

Save checked row of one dataGrid into another dataGrid

I have a simple datagrid which Stores the data returned in json format in it. I have added unbound checkbox column to it. Now I want to Store only the checked rows in another datagrid. How should I proceed.
My Code
protected void BtnSave_Click(object sender, EventArgs e)
{
foreach (DataGridItem item in this.gv1.Items)
{
CheckBox chkBox =
(CheckBox)item.FindControl("ChkRows");
//If it's selected then add it to our new Datagrid
if (chkBox != null && chkBox.Checked)
{
//save
}
}
}
datasource for 1st grid
SearchAPIRequest.defaultApiKey = "samplekey";
SearchAPIRequest request = new SearchAPIRequest(rawName: txtUser.Text);
try
{
SearchAPIResponse response = request.Send();
DataTable dt = new DataTable();
dt.Columns.Add("Website");
dt.Columns.Add("first");
dt.Columns.Add("last");
dt.Columns.Add("jobs");
dt.Columns.Add("dobs");
dt.Columns.Add("educations");
dt.Columns.Add("addresses");
dt.Columns.Add("images");
dt.Columns.Add("URL");
for (int i = 0; i < response.Records.Count; i++)
{
DataRow dr = dt.NewRow();
dr["Website"] = response.Records[i].Source.Domain;
dr["First"] = response.Records[i].Names[0].First;
dr["Last"] = response.Records[i].Names[0].Last;
dr["jobs"] = response.Records[i].Jobs.Count > 0 ? response.Records[i].Jobs[0].Display: "";
dr["dobs"] = response.Records[i].DOBs.Count > 0 ? response.Records[i].DOBs[0].DateRange.Start.ToString() : "";
dr["images"] = response.Records[i].Images.Count> 0 ? response.Records[i].Images[0].Url:"";
dr["educations"] = response.Records[i].Educations.Count > 0 ? response.Records[i].Educations[0].Display : "";
dr["addresses"] = response.Records[i].Addresses.Count > 0 ? response.Records[i].Addresses[0].Display: "";
dr["URL"] = response.Records[i].Source.Url;
dt.Rows.Add(dr);
}
gv1.DataSource = dt;// response.Records[0].AllFields.ToList();
gv1.DataBind();

Unable to modify a dataset before binding to gridview in asp.net

I need to modify a dataset before binding it to a gridview.
When I walk through the complete code block, and hover over dsEmployeeOrg, that records
dont appear modified. What am I missing here?
My code is:
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i].ItemArray[2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i].ItemArray[2] = "0000";
}
}
}
Please modify your code as below
DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);
DataTable dt = dsEmployeeOrg[0];
string sManagerID = "";
string sSupervisorID = "";
string sEmployeeID = "";
for (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)
{
sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();
sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();
sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();
if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))
{
if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())
{
// This is a Supervisor record
dt.Rows[i][2] = "1111";
}
else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())
{
//This is a Employee record
dt.Rows[i][2] = "0000";
}
}
}

Compare dataset column type

Here's the code :
try
{
string strReadDataLine;
strReadDataLine = sr.ReadLine();
while (strReadDataLine != null)
{
string[] strReadDataLineSplited = strReadDataLine.Split(';');
DataRow thisRow = thisDataSet.Tables["Repartition"].NewRow();
DataTable item = thisDataSet.Tables["Repartition"];
for (int i = 0; i < strDataLines.Length; i++)
{
DataColumn thisColomn =
thisDataSet.Tables["Repartition"].Columns[i];
// Here i need to know if the colomn is a string
if (thisColomn.DataType.ToString() == "System.String")
{
thisRow[strDataLines[i]] = strReadDataLineSplited[i];
}
}
thisRow["ID_USAGER"] = 1;
thisDataSet.Tables["Repartition"].Rows.Add(thisRow);
strReadDataLine = sr.ReadLine();
}
//thisDataAdapter.Update(thisDataSet, "Repartition");
}
What I need is to know if a column is a string to assign a data as string to the column. What I get is a argumentException saying "input string was not in correct format. couldn't store <2.111> in MY_FLOAT colomn. Expect type is double."
What I really need is to compare the column type to something to get the type then assign the column to the correct type.
I hope this is clear as my English is not so good.
If I understand correctly I built a functional copy of the code-fragment and fixed it to correctly handle the type conversion. You really only missed two things:
. #1 - You were indexing into the columns by ordinal and using that information to obtain the column type. Then setting the information you indexed the column my name. I corrected this with the introduction of the 'columnName' variable below.
. #2 - To properly convert the string input to the desired column type you only need to use the System.Convert.ChangeType(object, Type) method as shown below.
static void Main()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Repartition");
DataColumn col;
col = dt.Columns.Add("ID_USAGER", typeof(int));
col = dt.Columns.Add("TestString", typeof(string));
col = dt.Columns.Add("TestInt", typeof(int));
col = dt.Columns.Add("TestDouble", typeof(double));
string testData = "TestString;TestInt;TestDouble";
testData += Environment.NewLine + "Test1;1;1.1";
testData += Environment.NewLine + "Test2;2;2.2";
Test(ds, new StringReader(testData));
}
public static void Test(DataSet thisDataSet, StringReader sr)
{
string[] strDataLines = sr.ReadLine().Split(';');
string strReadDataLine;
strReadDataLine = sr.ReadLine();
while (strReadDataLine != null)
{
string[] strReadDataLineSplited = strReadDataLine.Split(';');
DataRow thisRow = thisDataSet.Tables["Repartition"].NewRow();
DataTable item = thisDataSet.Tables["Repartition"];
for (int i = 0; i < strDataLines.Length; i++)
{
string columnName = strDataLines[i];
//#1 Don't use this as Columns[i] may not be Columns[columnName]
//DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[i];
DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[columnName];
//#2 Assing to the results of the string converted to the correct type:
thisRow[strDataLines[i]] = System.Convert.ChangeType(strReadDataLineSplited[i], thisColomn.DataType);
}
thisRow["ID_USAGER"] = 1;
thisDataSet.Tables["Repartition"].Rows.Add(thisRow);
strReadDataLine = sr.ReadLine();
}
}

Categories

Resources